使用for循环和条件语句搜索python列表

时间:2015-02-05 21:26:55

标签: python python-2.7 for-loop conditional-statements

a = [1,1,1,4,4,4,5]
b = [20150602, 20150603, 20150604, 20150605, 20150606, 20150607,20150608]
c = zip(a,b)

output = []
for i in range(0, len(c)-1):
    if c[i][0] == c[i+1][0] and c[i+1][1] - c[i][1] <= 3:
        output.append(c[i])
print output

此代码使用条件搜索2个列表。如果列表中的元素n ==元素n + 1,则列表b中的AND(元素n + 1) - (元素n)&lt; = 3 ......它打印结果。我遇到的问题是它切断了应该打印的1个元素。 (即此代码将输出

[(1, 20150602), (1, 20150603), (4, 20150605), (4, 20150606)]

但应该输出

[(1, 20150602), (1, 20150603), (1,20150604), (4, 20150605), (4, 20150606), (4, 20150607)])

2 个答案:

答案 0 :(得分:0)

请参阅输出列表中的第二个附加内容。 :)

In [14]:

a = [1,1,1,4,4,4,5]
b = [20150602, 20150603, 20150604, 20150605, 20150606, 20150607,20150608]
c = zip(a,b)

output = []
for i in range(0, len(c)-1):
    if c[i][0] == c[i+1][0] and c[i+1][1] - c[i][1] <= 3:
        output.append(c[i])
        output.append(c[i+1])
    output = sorted(list(set(output)))
print output



[(1, 20150602), (1, 20150603), (1, 20150604), (4, 20150605), (4, 20150606), (4, 20150607)]

答案 1 :(得分:0)

a = [1,1,1,4,4,4,5]
b = [20150602, 20150603, 20150604, 20150605, 20150606, 20150607,20150608]
c = zip(a,b)

output = []
for i in range(0, len(c)-1):
    if c[i][0] == c[i+1][0] and c[i+1][1] - c[i][1] <= 3:
        output.append(c[i])
    elif c[i][0] != c[i+1][0]:
        print 'equality failed for numbers: %d and %d' % (c[i][0], c[i+1][0])
    elif c[i+1][1] - c[i][1] > 3:
        print 'Subtraction is greater than three for: %d and %d' % (c[i][1], c[i+1][1])

print output

输出:

equality failed for numbers: 1 and 4
equality failed for numbers: 4 and 5
[(1, 20150602), (1, 20150603), (4, 20150605), (4, 20150606)]

缺少两个元素的原因是因为for循环中的i为2 c[i][0]将返回1.现在,当执行if语句的这一部分时:c[i][0] == c[i+1][0]它返回false,因为c[i][0]返回1而c[i+1][0]返回4并且它们彼此不相等。当i等于5时也会发生同样的情况。