[英]How to add a value from one list to another but the former list has different number of elements
基本上有 3 個列表:list1、list2、list3
list1 和 list2 有 20 個元素,而 list3 有 10 個元素
我正在努力有效地做到這一點,但沒有錯誤
for x in range(0, len(list3)):
for i in range(0, len(list1)):
if list1[i] > 20:
list3[x] = list2[i]
問題是 list3 中的“舊”值被存儲,但在出現大於 20 的新值后被替換。
編輯:
list1 = [10,20,30,40,50,60,70,80,90,100]
list2 = [1,2,3,4,5,6,7,8,9,10]
list3 = zeros(5) # array3 = [0,0,0,0,0]
for x in range(0, len(list1)):
if list1[x] >50:
list3[x] = list2[x]
我想要的結果list3 = [6,7,8,9,10]
上面的代碼會產生error the element value is not high enough for list3
代碼應拒絕 list1 中低於 50 的任何值。 獲取list1中值大於50的元素,然后獲取list2中相同元素的值。 然后將這些值存儲到 list3
編輯 2:將數組更改為列表——我剛剛習慣於使用數組,我本能地使用這個詞來指代兩者。 我的錯
不需要將最終數組的列表歸零。 您可以將其設置為空列表並將每個結果附加到array3
。 編輯:您也在使用列表,而不是數組。
array1 = [10,20,30,40,50,60,70,80,90,100]
array2 = [1,2,3,4,5,6,7,8,9,10]
array3 = []
array3 = [array2[idx] for idx, value in enumerate(array1) if value > 50]
#[6, 7, 8, 9, 10]
每次匹配時,它會將位於array2
中索引x
處的值附加到array3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.