2017-06-17 40 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