检查列表中的整数是否重复,并且是否顺序

时间:2010-03-11 22:11:56

标签: python

testGroupList是一个整数列表。 我需要检查testGroupList中的数字是顺序的而不是重复的数字。忽略负整数。

例如,[1,2,-1,2,3,4]是一个错误,因为2是重复的,但是[-1,3,2,4,1,5]是可以的。

我按照以下方式实现了它,它非常难看。有没有聪明的方法来做到这一点?

    buff = filter(lambda x: x > 0, testGroupList) 
    maxval = max(buff) 
    for i in range(maxval): 
        id = i+1 
        val = buff.count(id) 
        if val == 1: print id, 
        elif val >= 2: print "(Test Group %d duplicated %d times)" % (id, val), 
        elif val == 0: print "(Test Group %d missing)" % id,

5 个答案:

答案 0 :(得分:1)

对于Python2.7或3.1,您可以使用Counter,尽管在Python3的情况下需要更改打印

from collections import Counter
counter = Counter(x for x in testGroupList if x>=0)
minval = min(Counter) 
maxval = max(Counter)
messages={0:"(Test Group %(id)d missing)",
          1:"%(id)d",
          2:"(Test Group %(id)d duplicated %(val)d times)"}
for id in range(minval,maxval+1): 
    val = counter[id]
    print(messages[min(val,2)]%vars())

对于较旧的Python,请使用defaultdict

from collections import defaultdict
counter = defaultdict(int)
for k in testGroupList:
    if k>=0:counter[k]+=1

minval = min(counter) 
maxval = max(counter)
messages={0:"(Test Group %(id)d missing)",
          1:"%(id)d",
          2:"(Test Group %(id)d duplicated %(val)d times)"}
for id in range(minval,maxval+1): 
    val = counter[id]
    print messages[min(val,2)]%vars(),

答案 1 :(得分:1)

如果你想在更小的代码中寻找更优雅,那么你可以这样做:

buff = [x for x in testGroupList if x > 0]
for i, val in enumerate([buff.count(x) for x in xrange(1,max(buff))]):
    if val == 1: print i+1, 
    elif val > 1: print "(Test Group %d duplicated %d times)" % (i+1, val), 
    elif val == 0: print "(Test Group %d missing)" % (i+1),

非常接近您的原件。我使用i而不是id,因为id是Python中的标准函数。

答案 2 :(得分:0)

for i, v in enumerate(buff):
    if i != v - 1:
        print "MISSING OR DUPLICATE"

答案 3 :(得分:0)

如果您不需要花哨的错误报告,那么您可以将其实现为两个简单的检查:

positiveValues = [x for x in testGroupList if x > 0]
if len(positiveValues) != len(set(positiveValues)):
    print("Input has duplicate values")
elif len(positiveValues) != max(positiveValues):
    print("Input has missing values")

答案 4 :(得分:0)

如果您只是想确定列表没有重复项,那么您可以使用列表的元素创建一个set(),并比较两者的长度。相同的长度意味着没有重复。

确定它们是否是连续的可以查看列表的最大值和最小值之差,该值应该小于长度的一个。

“设置差异”可用于查找缺失的整数。

以下是一些简明的定义:

def all_different(any_list):
    '''returns True if all items in the list are different.
    (Note: this assumes input is a list'''
    return len(any_list) == len(set(any_list))

def any_duplicate(any_list):
    '''returns True if any items in the list are repeated.
    (Note: this assumes input is a list'''
    return len(any_list) != len(set(any_list))

def sequential_ints(list_of_ints):
    '''returns True if input is a sequential list of ints.
    (Note: this assumes input is a list, and only of ints'''
    return len(list_of_ints)-1==max(list_of_ints)-min(list_of_ints)

def find_missing(list_of_ints):
    '''returns a list of any integers "missing", assuming 
    input was "supposed to be" sequential list of ints.
    (Note: this assumes input is a list, and only of ints'''
    return list( set(range(min(list_of_ints),max(list_of_ints)+1))-set(list_of_ints) )

此测试代码:

list1 = [1, 2, 3, 4, 5, 6]
print("all_different:", all_different(list1))
print("any_duplicate:", any_duplicate(list1))
print("sequential_ints:", sequential_ints(list1))
print("find_missing:   ", find_missing(list1))
print()

list2 = [1, 2, 3, 4, 5, 6, 2]
print("all_different:", all_different(list2))
print("any_duplicate:", any_duplicate(list2))
print("sequential_ints:", sequential_ints(list2))
print("find_missing:   ", find_missing(list2))
print()

list3 = [1, 3, 4, 6]
print("all_different:", all_different(list3))
print("any_duplicate:", any_duplicate(list3))
print("sequential_ints:", sequential_ints(list3))
print("find_missing:   ", find_missing(list3))

给出:

all_different: True
any_duplicate: False
sequential_ints: True
find_missing:    []

all_different: False
any_duplicate: True
sequential_ints: False
find_missing:    []

all_different: True
any_duplicate: False
sequential_ints: False
find_missing:    [2, 5]