首页 > 解决方案 > 如果存在重复值,如何返回 True 和 false

问题描述

我有一个清单:

list = ["A", "A", "B", "A", "C"]

和一个forif语句相结合:

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' outside function

也试过这个:

 for x in list:
    if any(x == "A" in x):
    return True
SyntaxError: expected an indented block

我想要的输出是:

True 因为"A"存在的重复项

标签: python

解决方案


可以使用Counter

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

推荐阅读