【问题标题】:Check whether there are duplicate values (which is > 0) in a list in Python检查Python中的列表中是否存在重复值(> 0)
【发布时间】:2017-03-08 17:33:34
【问题描述】:

我想检查数组列表中是否存在大于0的重复元素。

if [1,0,0,0,1,2] = true

if [0,0,0,0,0,0] = false 

我怎样才能得到这个结果?

【问题讨论】:

标签: python list


【解决方案1】:

我猜 OP 只想处理自然数。试试这个:

def is_duplicated_natural_numbers(input):
    # make it >0
    natural_numbers_list = list(filter(lambda x: x > 0, input))

    # remove duplicates
    set_list = list(set(natural_numbers_list))

    # if natural_numbers_list == set_list, no natural numbers duplicates
    return natural_numbers_list != set_list

print(is_duplicated_natural_numbers([1,0,0,0,1,2]))  # True
print(is_duplicated_natural_numbers([0,0,0,0,0,0]))  # False
print(is_duplicated_natural_numbers([1,2,3,4,5,1]))  # True

【讨论】:

    【解决方案2】:

    使用字典来记录元素的数量,如果一个元素出现两次(不为零),那么您的答案是正确的,所以只需跳出循环。

    试试这个:

    l = [0,0,0,0]
    dic = {}
    flag = False
    for i in l:
        if i in dic:
            dic[i]+=1
            if dic[i]>1 and i!=0:
                flag = True
                break
        else:
            dic[i] = 1
    print flag
    

    注意:有更好的方法,但这个方法很容易理解。

    【讨论】:

      猜你喜欢
      • 2017-08-22
      • 2019-05-28
      • 2018-06-19
      • 1970-01-01
      • 2015-01-18
      • 1970-01-01
      • 1970-01-01
      • 2019-03-19
      • 2015-03-06
      相关资源
      最近更新 更多