列表循环中的python上一个元素

2024-04-20 06:25:51 发布

您现在位置:Python中文网/ 问答频道 /正文

请帮忙解决这个问题。我需要将循环的一个元素与python3中的前一个元素进行比较。下面的代码给出了错误:

TypeError: 'int' object is not subscriptable

for index, (i, j) in enumerate(zip(a_list, b_list)):
    if j[index] == j[index-1]:
        a = 0

Tags: 代码in元素forindexobjectis错误
1条回答
网友
1楼 · 发布于 2024-04-20 06:25:51

ija_listb_list的元素,因此它们不是可以用[]访问的lists,而是简单的ints(大概)。你知道吗

为什么不这样做?你知道吗

data = [1, 2, 2, 3, 4, 5, 5, 5, 3, 2, 7]

for first, second in zip(data, data[1:]):
    if first == second:
        print('Got a match!')

输出:

Got a match!
Got a match!
Got a match!

相关问题 更多 >