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
但是,这不适合我。任何帮助将不胜感激。
非常感谢你这是更简单,它的工作原理。你的'with open('test.txt')为f: my_list = [int(i)for i in line.split()for line in f]'对我没用(名字'line'没有定义)但是当我使用我原本使用过的那一行版本 – Sekou
@Sekou:对不起,我换了'for's。编辑应该工作。 –
是的,现在它再次感谢 – Sekou