Python 如何比较列表中连续整数的最后几位?

Python 如何比较列表中连续整数的最后几位?,python,list,Python,List,在我正在创建的程序中,我需要将文件中的整数添加到列表中,然后确定每个整数的最后一位,并将其与下一个整数的最后一位进行比较,并在此循环中继续,直到将列表中的每个整数与下一个整数进行比较并存储结果。我可以将文件中的整数添加到列表中,并确定每个整数的最后一位,但无法比较最后一位。我一直在使用代码 with open('test.txt') as f: my_list = [] for line in f: my_list.extend(int(i) for i i

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

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

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

你把事情弄得太复杂了。首先,我们可以简单地编写解析器,如下所示:

with open('test.txt') as f:
    my_list = [int(i) for line in f for i in line.split()]
接下来,我们可以使用
zip(my_list,my_list[1:])
来同时迭代当前项和下一项,而不是以那种复杂的方式构建
nextem

for n0,n1 in zip(my_list,my_list[1:]):
    pass
当然,现在我们仍然需要处理计数。但是,我们可以使用
集合
库的
计数器
来实现这一点。比如:

from collections import Counter

ctr = Counter((n0%10,n1%10) for n0,n1 in zip(my_list,my_list[1:]))
因此,我们甚至不需要
for
循环。现在,
计数器是字典。它将元组
(i,j)
映射到以
i
结尾的数字的计数
cij
,然后是以
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

非常感谢,它简单多了,而且很有效。您的
将open('test.txt')作为f:my_list=[int(i)for i in line.split()for line in f]
对我不起作用(名称“line”未定义),但当我使用该行的最初版本时worked@Sekou:对不起,我把
换成了
s。编辑应该是有效的。