所以我正在尝试制作这个程序,它会要求用户输入并将值存储在数组/列表中。
然后当输入空行时,它会告诉用户这些值中有多少是唯一的。
我构建这个是出于现实生活的原因,而不是作为一个问题集。
enter: happy
enter: rofl
enter: happy
enter: mpg8
enter: Cpp
enter: Cpp
enter:
There are 4 unique words!
我的代码如下:
# ask for input
ipta = raw_input("Word: ")
# create list
uniquewords = []
counter = 0
uniquewords.append(ipta)
a = 0 # loop thingy
# while loop to ask for input and append in list
while ipta:
ipta = raw_input("Word: ")
new_words.append(input1)
counter = counter + 1
for p in uniquewords:
..到目前为止我只知道这么多。< br >我不确定如何计算列表中的唯一字数?< br >如果有人可以张贴解决方案,以便我可以从中学习,或者至少向我展示它会有多棒,谢谢!
此外,使用集合。重构代码的计数器:
from collections import Counter
words = ['a', 'b', 'c', 'a']
Counter(words).keys() # equals to list(set(words))
Counter(words).values() # counts the elements' frequency
输出:
['a', 'c', 'b']
[2, 1, 1]
您可以使用集合来删除重复项,然后使用len函数来计算集合中的元素数:
len(set(new_words))
值,计数=np。唯一(words,return_counts=True)
import numpy as np
words = ['b', 'a', 'a', 'c', 'c', 'c']
values, counts = np.unique(words, return_counts=True)
函数numpy.unique返回输入列表的排序唯一元素及其计数:
['a', 'b', 'c']
[2, 1, 3]