Reputation: 163
I want to increase certain elements in I1
by 1
according to locations specified by T
. I present the current and expected outputs.
I1= [17, 19, 30, 31, 34, 46]
T=[1, 5]
New=[i+1 for i in I1 if i in T]
print(New)
The current output is
[]
The expected output is
I1= [17, 20, 30, 31, 34, 47]
Upvotes: 0
Views: 92
Reputation: 24059
Use enumerate
and if/else
in list_comprehension
.
# We can save a set of T if we have repeated items in 'T' and if 'I1' is a large array
set_T = set(T)
New = [item+1 if idx in set_T else item for idx, item in enumerate(I1)]
print(New)
Output:[17, 20, 30, 31, 34, 47]
Upvotes: 3
Reputation: 114440
This sort of thing is much easier in numpy:
I1 = np.array(I1)
I1[T] += 1
Upvotes: 2