My goal is to print the value of the elements in the list where the consecutive elements are changed. For instance, if the given input is 1 1 1 3 3 3 2
then the output should be [1,3,3,2]
, because in the input you can see that the value of 1 is changing to 3, so 1 and 3 should be appended to the list, and also the value of 3 is changing to 2, so 3 and 2 should also be appended to the list.
The required output is [1,3,3,2]
.
However, my code is returning only [1,3]
but not [3,2]
. I don't understand why?
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)
CodePudding user response:
The for i in a
will iterate the values in a
, not the indices. That is why you get unexpected results, and could even run into an error.
You can use zip
to get two consecutive values, and then you turn this into a list comprehension:
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]
CodePudding user response:
Code:
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)
Output:
[1, 3, 3, 2]
CodePudding user response:
As a follow up to @trincot's answer, you can achieve the same thing more clearly / explicitly, as follows:
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) ]
Note: chain.from_iterable()
will convert [(1, 3), (3, 2)]
into the desired [1, 3, 3, 2]
.