【问题标题】:How do I count occurrence of unique values inside a list如何计算列表中的唯一值
【发布时间】:2012-08-30 05:16:31
【问题描述】:

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

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:

..这就是我到目前为止所获得的全部内容。
我不确定如何计算列表中的唯一单词数?
如果有人可以发布解决方案,以便我可以从中学习,或者至少向我展示它会有多好,谢谢!

【问题讨论】:

    标签: python arrays variables loops unique


    【解决方案1】:

    此外,使用collections.Counter 重构您的代码:

    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]
    

    【讨论】:

    • 不是乔尔问题的答案,而是正是我正在寻找的,谢谢!
    • 完美。和一个牛眼。谢谢@Vidul
    • Counter(words).values() 很好。我们假设计数是按照单词列表的第一次出现的顺序?我的意思是,我假设计数会给我们一个计数,然后是 b,然后是 c,然后是 d...
    • 请注意,如果您想将其表示为像count_dict = {'a': 2, 'b': 1, 'c': 1} 这样的字典,您可以使用count_dict = dict(Counter(words).items())
    • @Peter .items() 不需要。 dict(Counter(words))
    【解决方案2】:

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

    len(set(new_words))
    

    【讨论】:

      【解决方案3】:

      values, counts = np.unique(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]
      

      【讨论】:

      • stackoverflow.com/a/12282286/2932052 四年后 - 是什么让这个解决方案变得更好?
      • 它提供了更精细的信息。
      • 通过至少提供指向建议函数的documentation 的链接,在答案中付出额外的努力总是很好的。
      • @Jeyekomon 是的,一个不错的补充。如果您愿意,可以编辑答案。
      【解决方案4】:

      使用set

      words = ['a', 'b', 'c', 'a']
      unique_words = set(words)             # == set(['a', 'b', 'c'])
      unique_word_count = len(unique_words) # == 3
      

      有了这个,您的解决方案可以很简单:

      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
      

      【讨论】:

      • 很好的解释,有时最好先一步完成,这样cmets就有足够的空间;)
      【解决方案5】:
      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}
      

      【讨论】:

      • 请解释这与其他答案有何不同
      • 这就像Counter,但效率很低,因为大多数计数都被丢弃了,list.count() 无论如何都是 O(n)。您甚至根本不需要将aa 转换为列表。请参阅Vidul's answer
      【解决方案6】:

      对于 ndarray,有一个名为 unique 的 numpy 方法:

      np.unique(array_name)
      

      例子:

      >>> 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()

      Series_name.value_counts()
      

      【讨论】:

        【解决方案7】:

        如果你想要一个唯一值的直方图,这里是 oneliner

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

        【讨论】:

          【解决方案8】:

          怎么样:

          import pandas as pd
          #List with all words
          words=[]
          
          #Code for adding words
          words.append('test')
          
          
          #When Input equals blank:
          pd.Series(words).nunique()
          

          它返回一个列表中有多少个唯一值

          【讨论】:

          • 欢迎来到 StackOverflow!看起来这个解决方案假设使用pandas 框架。最好在答案中提及它,因为其他用户可能不清楚。
          【解决方案9】:
          ipta = raw_input("Word: ") ## asks for input
          words = [] ## creates list
          unique_words = set(words)
          

          【讨论】:

            【解决方案10】:

            虽然集合是最简单的方法,但您也可以使用 dict 并使用 some_dict.has(key) 来填充只有唯一键和值的字典。

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

            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
            

            【讨论】:

              【解决方案11】:

              使用 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"])
              

              然后您可以以任何您想要的格式导出结果

              【讨论】:

                【解决方案12】:

                以下应该有效。 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'
                

                【讨论】:

                  【解决方案13】:

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

                  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!"
                  

                  【讨论】:

                    【解决方案14】:
                    ipta = raw_input("Word: ") ## asks for input
                    words = [] ## creates list
                    
                    while ipta: ## while loop to ask for input and append in list
                      words.append(ipta)
                      ipta = raw_input("Word: ")
                      words.append(ipta)
                    #Create a set, sets do not have repeats
                    unique_words = set(words)
                    
                    print "There are " +  str(len(unique_words)) + " unique words!"
                    

                    【讨论】:

                      【解决方案15】:

                      你可以使用get方法:

                      lst = ['a', 'b', 'c', 'c', 'c', 'd', 'd']
                      
                      dictionary = {}
                      for item in lst:
                          dictionary[item] = dictionary.get(item, 0) + 1
                          
                      print(dictionary)
                      

                      输出:

                      {'a': 1, 'b': 1, 'c': 3, 'd': 2}
                      

                      【讨论】:

                        【解决方案16】:

                        这是我自己的版本

                        def unique_elements():
                            elem_list = []
                            dict_unique_word = {}
                            for i in range(5):# say you want to check for unique words from five given words
                                word_input = input('enter element: ')
                                elem_list.append(word_input)
                                if word_input not in dict_unique_word:
                                    dict_unique_word[word_input] = 1
                                else:
                                    dict_unique_word[word_input] += 1
                            return elem_list, dict_unique_word
                        result_1, result_2 = unique_elements() 
                        # result_1 holds the list of all inputted elements
                        # result_2 contains unique words with their count
                        print(result_2)
                        

                        【讨论】:

                        • 您能否解释一下您的代码以及如何解决所提出的问题?
                        • 好的。该代码接收用户设置的输入范围,将它们附加到elem_list,并使用dict_unique_word 字典来获取接收到的唯一单词的数量。
                        猜你喜欢
                        • 2019-05-15
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 2021-11-12
                        相关资源
                        最近更新 更多