检测连续列表元素中的更改不起作用



我的目标是打印列表中连续元素被更改的元素的值。例如,如果给定的输入是1 1 1 3 3 3 2,那么输出应该是[1,3,3,2],因为在输入中你可以看到1的值变成了3,所以1和3应该被添加到列表中,并且3的值也变成了2,所以3和2也应该被添加到列表中。

要求输出为[1,3,3,2]。然而,我的代码只返回[1,3]而不返回[3,2]。我不明白为什么?

for t in range(int(input())):
n = int(input())
a = list(map(int,input().split()))[:n]
l=[]
if a.count(a[0])==len(a):
print("0")
else:
for i in a:
if a[i] != a[i+1]:
print(i)
l.extend((a[i],a[i+1]))
print(l)

代码:

a = [1, 1, 1, 3, 3, 3, 2]
output = []
for i in range(len(a) - 1):
if a[i] != a[i + 1]:
output.append(a[i])
output.append(a[i+1])
print(output)

输出:

[1, 3, 3, 2]

for i in a将迭代a中的,而不是索引。这就是为什么您会得到意想不到的结果,甚至可能遇到错误。

您可以使用zip来获得两个连续的值,然后将其转换为列表推导式:

a = [1,1,1,3,3,3,2]
l = [k 
for i, j in zip(a, a[1:]) 
for k in (i, j) 
if i != j]

作为@trincot回答的后续,您可以更清楚/明确地实现同样的事情,如下所示:

from itertools import chain
# input data
a = [1,1,1,3,3,3,2]
# get a list of all pairs ( N , N+1 )
pairs = zip(a, a[1:])
# filter the list, keeping only the changes
changes = filter(lambda v: v[0] != v[1], pairs)
# flatten the retained changes into a simple list
l = [ *chain.from_iterable(changes) ]

注意:chain.from_iterable()[(1, 3), (3, 2)]转换成所需的[1, 3, 3, 2]

相关内容