Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何计算列表中的唯一值_Python_Arrays_Variables_Loops_Unique - Fatal编程技术网

Python 如何计算列表中的唯一值

Python 如何计算列表中的唯一值,python,arrays,variables,loops,unique,Python,Arrays,Variables,Loops,Unique,因此,我试图制作一个程序,要求用户输入并将值存储在数组/列表中。 然后,当输入一个空行时,它将告诉用户这些值中有多少是唯一的。 我建立这个是为了现实生活的原因,而不是作为一个问题集 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: ") #

因此,我试图制作一个程序,要求用户输入并将值存储在数组/列表中。
然后,当输入一个空行时,它将告诉用户这些值中有多少是唯一的。
我建立这个是为了现实生活的原因,而不是作为一个问题集

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:
…这就是我到目前为止所得到的一切。
我不知道如何计算列表中唯一的字数?
如果有人可以发布解决方案,这样我就可以从中学习,或者至少向我展示它是多么棒,谢谢

您可以使用删除重复项,然后使用函数对集合中的元素进行计数:

len(set(new_words))
使用:

有了这一点,您的解决方案可以简单到:

words = []
ipta = raw_input("Word: ")

while ipta:
  words.append(ipta)
  ipta = raw_input("Word: ")

unique_word_count = len(set(words))

print "There are %d unique words!" % unique_word_count

以下几点应该行得通。lambda函数过滤掉重复的单词

inputs=[]
input = raw_input("Word: ").strip()
while input:
    inputs.append(input)
    input = raw_input("Word: ").strip()
uniques=reduce(lambda x,y: ((y in x) and x) or x+[y], inputs, [])
print 'There are', len(uniques), 'unique words'

我自己也会用一套,但还有另一种方法:

uniquewords = []
while True:
    ipta = raw_input("Word: ")
    if ipta == "":
        break
    if not ipta in uniquewords:
        uniquewords.append(ipta)
print "There are", len(uniquewords), "unique words!"
此外,用于重构代码:

输出:

['a',c',b']
[2, 1, 1]

尽管集合是最简单的方法,但您也可以使用dict和
某些dict.has(key)
来仅使用唯一的键和值填充字典

假设您已经使用用户的输入填充了
words[]
,创建一个dict,将列表中的唯一单词映射到一个数字:

word_map = {}
i = 1
for j in range(len(words)):
    if not word_map.has_key(words[j]):
        word_map[words[j]] = i
        i += 1                                                             
num_unique_words = len(new_map) # or num_unique_words = i, however you prefer

对于ndarray,有一个名为:

示例:

>>> np.unique([1, 1, 2, 2, 3, 3])
array([1, 2, 3])
>>> a = np.array([[1, 1], [2, 3]])
>>> np.unique(a)
array([1, 2, 3])
对于一个系列,有一个函数调用:


value,counts=np.unique(words,return\u counts=True)

使用pandas的其他方法

import pandas as pd

LIST = ["a","a","c","a","a","v","d"]
counts,values = pd.Series(LIST).value_counts().values, pd.Series(LIST).value_counts().index
df_results = pd.DataFrame(list(zip(values,counts)),columns=["value","count"])
然后,您可以将结果导出为所需的任何格式

如何:

aa="XXYYYSBAA"
bb=dict(zip(list(aa),[list(aa).count(i) for i in list(aa)]))
print(bb)
# output:
# {'X': 2, 'Y': 3, 'S': 1, 'B': 1, 'A': 2}
import pandas as pd
#List with all words
words=[]

#Code for adding words
words.append('test')


#When Input equals blank:
pd.Series(words).nunique()

它返回列表中的唯一值的数量

如果您想获得唯一值的直方图,这里是oneliner

import numpy as np    
unique_labels, unique_counts = np.unique(labels_list, return_counts=True)
labels_histogram = dict(zip(unique_labels, unique_counts))

不是对乔尔问题的回答,而是我想要的,谢谢!完美的还有一只公牛的眼睛。谢谢@Vidul
计数器(words)。values()
很好。我们假设计数是按照单词列表第一次出现的顺序?我的意思是,我假设计数会给我们a的计数,然后是b,然后是c,然后是d…注意,如果你想把它表示为一个dict,比如
count\u dict={'a':2,'b':1,'c':1}
你可以做
count\u dict=dict(Counter(words).items())
@Peter
,items()
是不需要的
dict(Counter(words))
请解释这与其他答案有什么不同。这就像是一个
计数器
,但效率很低,因为大多数计数都被丢弃,而且
list.count()
无论如何都是O(n)。您甚至不需要将
aa
转换为list。请参见。欢迎来到StackOverflow!看起来这个解决方案假设使用
pandas
框架。最好在回答中提到它,因为其他用户可能不太清楚。是的:
np=Numpy
?是的:
四年后将Numpy导入为np
-是什么让这个解决方案更好?它提供了更精确的信息。很好的解释,有时最好先做一步,因此有足够的评论空间;)
>>> np.unique([1, 1, 2, 2, 3, 3])
array([1, 2, 3])
>>> a = np.array([[1, 1], [2, 3]])
>>> np.unique(a)
array([1, 2, 3])
Series_name.value_counts()
import pandas as pd

LIST = ["a","a","c","a","a","v","d"]
counts,values = pd.Series(LIST).value_counts().values, pd.Series(LIST).value_counts().index
df_results = pd.DataFrame(list(zip(values,counts)),columns=["value","count"])
aa="XXYYYSBAA"
bb=dict(zip(list(aa),[list(aa).count(i) for i in list(aa)]))
print(bb)
# output:
# {'X': 2, 'Y': 3, 'S': 1, 'B': 1, 'A': 2}
import pandas as pd
#List with all words
words=[]

#Code for adding words
words.append('test')


#When Input equals blank:
pd.Series(words).nunique()
import numpy as np    
unique_labels, unique_counts = np.unique(labels_list, return_counts=True)
labels_histogram = dict(zip(unique_labels, unique_counts))