如何比较列表中连续整数的最后数字?

时间:2017-06-17 15:49:15

标签: python list

在我创建的程序中,我需要将文件中的整数添加到列表中,然后确定每个整数的最后一位数,并将其与下一个整数的最后一位数进行比较,并在此循环中继续直到列表中的每个整数与下一个整数进行比较并存储结果。我能够将文件中的整数添加到列表中并确定每个整数的最后一位数,但我无法比较最后的数字。我一直在使用代码,

with open('test.txt') as f:
    my_list = []
    for line in f:
           my_list.extend(int(i) for i in line.split())

for elem in my_list:
    nextelem = my_list[my_list.index(elem)-len(my_list)+1]

one_followed_by_1 = 0
one_followed_by_2 = 0
one_followed_by_3 = 0
one_followed_by_4 = 0

for elem in my_list:
    if elem > 9:
        last_digit = elem % 10
        last_digit_next = nextelem % 10
        if last_digit == 1 and last_digit_next == 1:
            one_followed_by_1 += 1
        elif last_digit == 1 and last_digit_next == 2:
            one_followed_by_2 += 1
        elif last_digit == 1 and last_digit_next == 3:
            one_followed_by_3 += 1
        elif last_digit == 1 and last_digit_next == 4:
            one_followed_by_4 += 1

print one_followed_by_1
print one_followed_by_2
print one_followed_by_3
print one_followed_by_4

但这对我不起作用。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:3)

你让事情变得太复杂了。首先,我们可以简单地编写解析器:

with open('test.txt') as f:
    my_list = [int(i) for line in f for i in line.split()]

接下来,我们可以使用nextelem来同时迭代当前和下一个项目,而不是构建一个复杂方式的zip(my_list,my_list[1:])

for n0,n1 in zip(my_list,my_list[1:]):
    pass

当然,我们仍然需要处理计数。但是,我们可以使用Counter库的collections执行此操作。像:

from collections import Counter

ctr = Counter((n0%10,n1%10) for n0,n1 in zip(my_list,my_list[1:]))

所以我们甚至不需要for循环。现在Counter是一本字典。它会将{strong>元组(i,j) 映射到以cij结尾的数字的数量i,后跟一个以j结尾的数字

例如,打印数字,例如:

print ctr[(1,1)] # 1 followed by 1
print ctr[(1,2)] # 1 followed by 2
print ctr[(1,3)] # 1 followed by 3
print ctr[(1,4)] # 1 followed by 4

或完整的程序:

from collections import Counter

with open('test.txt') as f:
    my_list = [int(i) for line in f for i in line.split()]

ctr = Counter((n0%10,n1%10) for n0,n1 in zip(my_list,my_list[1:]))

print ctr[(1,1)] # 1 followed by 1
print ctr[(1,2)] # 1 followed by 2
print ctr[(1,3)] # 1 followed by 3
print ctr[(1,4)] # 1 followed by 4