Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/362.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中使用count()函数中的OR运算符_Python_List_Count_Conditional Operator - Fatal编程技术网

在Python中使用count()函数中的OR运算符

在Python中使用count()函数中的OR运算符,python,list,count,conditional-operator,Python,List,Count,Conditional Operator,我是Python新手。我有一个列表,上面写着x=['abc','cde','tar','har','yyu'] 我想数一数“abc”或“tar”出现的次数,我想找到的是 count1 = x.count('abc'or'tar') print(count1) 我希望答案是2,但答案是1。我在stackoverflow中搜索了其他代码。还有别的方法吗?提前谢谢这个怎么样 count1 = x.count('abc') + x.count('tar') print(count1) x.count

我是Python新手。我有一个列表,上面写着
x=['abc','cde','tar','har','yyu']
我想数一数“abc”或“tar”出现的次数,我想找到的是

count1 = x.count('abc'or'tar')
print(count1)
我希望答案是2,但答案是1。我在stackoverflow中搜索了其他代码。还有别的方法吗?提前谢谢

这个怎么样

count1 = x.count('abc') + x.count('tar')
print(count1)
x.count('abc'或'tar')
给你1,因为
'abc'或'tar'='abc'
您的搜索等于
x.count('abc')


最简单的方法是
x.count('abc')+x.count('tar')
列表。count
仅接受单个值作为参数

count(value, /) method of builtins.list instance
    Return number of occurrences of value.
您可以使用@adrtam提供的解决方案,也可以使用带生成器表达式的
sum
函数

>>> x = ['abc','cde','tar','har','yyu']
>>> sum(1 for i in x if i in ('abc', 'tar'))

的使用与您的想法不同。。。
'abc'或'tar'
的Pythonic评估是
'abc'
,因此您的代码实际上与以下代码相同:

count1 = x.count('abc')
print(count1)
要获得两者的总和,必须为搜索的每个字符串调用
count()
例程。因此,您可以使用:

count1 = x.count('abc') + x.count('tar')
print(count1)
如果要检查多个字符串,可以执行以下简单循环:

count = 0
for stringy in ('abc', 'tar',): # and others
    count += x.count(stringy)
print(count)

快乐编码

多谢各位。但这是一个例子。我试图做的是从文本文件中读取。说(1)‘abc’、‘edf’(2)‘abc’、‘tar’。现在“abc”来了两次,“tar”来了一次。对于(2),“abc”和“焦油”都来了,所以我不想重复计算它们。如果他们都来了,我想数一数。所以我希望我的答案是2,但使用+运算符会得到3。@SataMukherjee-你现在说的逻辑与你在问题中发布的逻辑不同。我想我已经回答了你原来的问题。如果你需要进一步的帮助,请发布一个新的问题。