2017-06-17 41 views
1

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

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 

但是,这不适合我。任何帮助将不胜感激。

回答

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 

当然现在我们仍然需要处理计数。但是,我们可以使用collections库的Counter来做到这一点。像:

from collections import Counter 

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

所以我们甚至不需要for循环。现在Counter是一本字典。它映射元组(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 
+0

非常感谢你这是更简单,它的工作原理。你的'with open('test.txt')为f: my_list = [int(i)for i in line.split()for line in f]'对我没用(名字'line'没有定义)但是当我使用我原本使用过的那一行版本 – Sekou

+0

@Sekou:对不起,我换了'for's。编辑应该工作。 –

+0

是的,现在它再次感谢 – Sekou