【问题标题】:Count unique element in a list [duplicate]计算列表中的唯一元素[重复]
【发布时间】:2020-06-27 15:46:36
【问题描述】:

我的问题是要求用户一次输入一个世界,看看用户知道多少个独特的世界(重复的单​​词不会计算在内) 例如

Word: Chat
Word: Chien
Word: Chat
Word: Escargot
Word: 
You know 3 unique word(s)!

以下是我现在拥有的:

count = 0
listword = []
word = input("Word: ")
while word != "":
    for i in listword:
            if i != word:
            listword.append(word)
        count += 1
    word = input("Word: ")
print("You know "+count+"unique word(s)!")

但是输出是这样的:

Word: hello
Word: hi
Word: hat
Word: 
You know  0  unique word(s)!

如何调整我的代码,为什么 count 仍然 =0?

【问题讨论】:

  • set
  • 您可以在此处使用set 而不是list 并返回该集合的长度。
  • 你听说过collections.Counter吗?
  • @ZavenZareyan 在这里不是很有用。使用set 就足够且高效。
  • 这能回答你的问题吗? Get unique values from a list in python

标签: python


【解决方案1】:

问题是listword 最初是空的,除非输入的单词与listword 中已有的单词不匹配,否则不会添加任何内容。如果在listword 中找不到该词,您真正想要做的是添加该词。

您可以使用list 做到这一点,但set 会更有效:

listword = set()
word = input("Word: ")
while word.strip() != "":
    if word not in listword:
        listword.add(word)
    word = input("Word: ")
print("You know", len(listword), "unique word(s)!")

【讨论】:

  • 谢谢!以前从未听说过 set,所以我不知道该怎么做
【解决方案2】:

我建议使用collections.Counter。这提供了一种简单的 Pythonic 方法来计算总计数,并在标准库中提供。

你可以这样使用它:

from collections import Counter

total_counts = Counter()
word = input("Word: ")
while word:
    total_counts.update([word])
    word = input("Word: ")
print("You know {:d} unique word(s)!".format(len(total_counts)))

【讨论】:

  • 这如何比内置的set更好地解决给定的问题?
  • 它并没有更好地解决它,但它可以工作并提供扩展脚本使用的能力。我也喜欢宣传 python 内置插件。
  • 随时通过set 实现提供答案。如果它是干净的,我会很高兴地支持它。
  • 我添加了一个答案。
【解决方案3】:

编辑您的代码即可:

listword = []
word = input("Word: ")
while word: # empty strings are equal to false as a boolean, and anything in them is equal to true
    if word not in listword:
        listword.append(word)
    word = input("Word: ")
print("You know ",len(listword),"unique word(s)!")

虽然如果我是你,我会研究一种更 Pythonic 的方式。

【讨论】:

  • 更多pythonic方式意味着使用set?以前从未听说过,所以不知道该怎么做,但还是谢谢!
【解决方案4】:

从一开始就声明一个空列表:

listword = []

并且只在这个循环内附加项目:

for i in listword:

你永远不会进入这个循环,因为列表总是空的,因此你永远不会循环通过count += 1

所以你应该添加另一个检查列表是否为空:

while word != "":
    if len(listword) == 0:
        listword.append(word)
        count+=1
    for i in listword:
            if i != word:
#...

【讨论】:

  • 鼓励这种不良的代码编写习惯并不是一个好主意。
  • 如果您不同意,请不要投反对票。即使你他的代码不是最好的,我的目标是查明他做错了什么,这样他就可以学习然后改进他的编码。只给出一个好的代码块而不解释错误是一个坏习惯。
  • 代码很差;这不是不同意的情况,而是您教他们做的事情不是好的做法,因此对答案投反对票会减少他们看到或尝试使用它的机会。
【解决方案5】:

此代码与您的代码相同,稍作修改。

count = 0
listword = []
word = input("Word: ")

while word != "":
    found= False
    for i in listword:
        if i == word:
            found= True
    if not found:
        listword.append(word)
    word = input("Word: ")
print("You know "+str(len(listword))+" unique word(s)!")

【讨论】:

  • 为什么要鼓励这样的不良做法?无需迭代 listword 以检查它是否包含 word
猜你喜欢
  • 1970-01-01
  • 2017-11-09
  • 2023-03-11
  • 2011-05-07
  • 1970-01-01
  • 2019-08-01
  • 2020-02-22
  • 2019-09-05
  • 1970-01-01
相关资源
最近更新 更多