我有一个列表:
list = ["A", "A", "B", "A", "C"]
和 for 和 if 语句组合:
for x in list:
if "A" in x:
print("true")
以上代码的输出:
true
true
接下来,我想知道如何告诉我列表中有重复的 "A" 并返回 True 的值
这是我尝试过的:
for x in list:
if any(x == "A" in x):
return True
但是出现错误: SyntaxError: 'return' 外部函数
也试过这个:
for x in list:
if any(x == "A" in x):
return True
SyntaxError: expected an indented block
我想要的输出是:
真 因为 "A" 存在重复项
请您参考如下方法:
可以使用计数器:
from collections import Counter
# hold in a 'dictionary' style something like: {'A':2, 'B':1, 'C':2}
c = Counter(['A','A','B', 'C', 'C'])
# check if 'A' appears more than 1 time. In case there is no 'A' in
# original list, put '0' as default.
c.get('A', 0) > 1 #
>> True
