簡體   English   中英

在 Python 的列表中將某些元素加 1

[英]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中使用enumerateif/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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM