如果存在重复值,如何返回True和false

时间:2019-10-18 07:50:35

标签: python

我有一个列表:

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"的重复项

4 个答案:

答案 0 :(得分:4)

可以使用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

答案 1 :(得分:1)

return用于从功能块之外的功能返回一个值,该值将不起作用。

对于给定的列表,[1,2,3,4,1,1,3] .count(element)将返回出现的次数,如果该数目大于1,则请确保其具有重复项

您可以尝试这样

for x in list:
    if "A" in x:
        print("true")
        print(list.count("A")) #count will return more that 1 if there are duplicates

答案 2 :(得分:1)

此代码应能解决问题:

def duplicate(mylist):
    for item in mylist:
        if mylist.count(item) > 1:
            return True
    return False

答案 3 :(得分:1)

返回仅在函数内部起作用。

尝试一下:

请参见here

def test(_list):
        d = {x:_list.count(x) for x in _list}
        result = [x for x in d.values()]
        if any(i > 1 for i in d.values()): 
            return True
        else: return False

_list = ["A", "A", "B", "A", "C"]  
print( test(_list) )