list - 将列表中的多个元素添加到 list.count (Python)

标签 list python-2.7

对于有点模糊的标题,我深表歉意,我会尝试在这里解释更多。

目前,我有以下代码,它计算值“y”和“n”出现在名为“结果”的列表中的次数。

NumberOfA = results.count("y")
NumberOfB = results.count("n")

是否有一种方法可以使诸如“yes”之类的值也计入 NumberOfA?我正在思考以下内容:

NumberOfA = results.count("y" and "yes" and "Yes")
NumberOfB = results.count("n" and "no" and "No")

但这行不通。这可能是一个很容易解决的问题,但是嘿。预先感谢!

最佳答案

至于为什么你上面的答案不起作用,这是因为Python只会取你传入的表达式的最终值:

>>> 'Yes' and 'y' and 'yes'
'yes'

因此,您的 count 将关闭,因为它只是在寻找最终值:

>>> results.count('yes' and 'y')
1
>>> results.count('yes' and '???')
0

这样的东西有用吗?请注意,这取决于列表中是否只有“是/否”式的答案(如果其中包含诸如“是的...嗯不”之类的内容,则将是错误的):

In [1]: results = ['yes', 'y', 'Yes', 'no', 'NO', 'n']

In [2]: yes = sum(1 for x in results if x.lower().startswith('y'))

In [3]: no = sum(1 for x in results if x.lower().startswith('n'))

In [4]: print yes, no
3 3

总体思路是获取结果列表,然后迭代每个项目,将其小写,然后获取第一个字母 (startswith) - 如果该字母是 y,我们知道它是;否则,它将是no

如果您愿意,您还可以通过执行以下操作来组合上述步骤(请注意,这需要 Python 2.7):

>>> from collections import Counter
>>> results = ['yes', 'y', 'Yes', 'no', 'NO', 'n']
>>> Counter((x.lower()[0] for x in results))
Counter({'y': 3, 'n': 3})

Counter 对象可以像字典一样对待,因此您现在基本上拥有一个包含 yesno 计数的字典> 的。

关于list - 将列表中的多个元素添加到 list.count (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14087752/

相关文章:

Python MySql 选择单列返回奇怪的值

Python 2.7 cx_freeze : What are the risks of removing the encodings that I dont need?

python - 阻止 Pandas TimeGrouper 形成不完整的组

c# - 访问另一个类中列表的元素

python - 在python中复制列表

python - 为什么不能列出[:] be embedded in list[:]. remove()?

python-2.7 - 如何在 kivy 中创建超链接?

python - 如何在 matplotlib 直方图中选择 bin

python在多个循环中迭代多个列表

python - 从Python中的字符串列表中获取小数/整数之前的所有值