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]
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]
This sort of thing is much easier in numpy:
I1 = np.array(I1)
I1[T] += 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.