簡體   English   中英

如何比較列表中連續整數的最后數字?

[英]How to compare the last digits of consecutive integers in a 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

但那不適合我。 任何幫助將不勝感激。

你讓事情變得太復雜了。 首先,我們可以簡單地編寫解析器:

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:])來同時迭代當前和下一個項目而不是構建復雜方式的nextelem

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM