[英]Increase certain elements by 1 in a list in Python
我想根據T
指定的位置將I1
中的某些元素增加1
。 我介紹了當前和預期的輸出。
I1= [17, 19, 30, 31, 34, 46]
T=[1, 5]
New=[i+1 for i in I1 if i in T]
print(New)
當前的 output 是
[]
預期的 output 是
I1= [17, 20, 30, 31, 34, 47]
在list_comprehension
中使用enumerate
和if/else
。
# 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]
這種事情在 numpy 中要容易得多:
I1 = np.array(I1)
I1[T] += 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.