簡體   English   中英

如何按索引比較 python 中的兩個列表

[英]how do I compare two lists in python by indexes

我必須按索引比較兩個列表,如果列表 1 中的索引等於 0,則列表 2 中的所有元素都為 0。

list1 = [0, 1, 1, 0]   # that's for example 
list2 = [[15, 19, 13, 15, 30, 14, 14], [14, 22, 30, 19, 29, 17, 15], [19, 21, 11, 25, 23, 23, 30], [15, 15, 25, 18, 22, 24, 29], [24, 30, 30, 11, 25, 18, 27]]

output:

list2 = [[0, 0, 0, 0, 0, 0, 0], [14, 22, 30, 19, 29, 17, 15], [19, 21, 11, 25, 23, 23, 30], [0, 0, 0, 0, 0, 0, 0]]
list1 = [0, 1, 1, 0] 
list2 = [[15, 19, 13, 15, 30, 14, 14], [14, 22, 30, 19, 29, 17, 15], [19, 21, 11, 25, 23, 23, 30], [15, 15, 25, 18, 22, 24, 29], [24, 30, 30, 11, 25, 18, 27]]
new_list=[]
for i in list1:
  for index,j in enumerate(list2):
    if(i==index):
      new_list.append([x*i for x in j] )
      break 
print(new_list)

這也應該這樣做:

list1 = [0, 1, 1, 0]   # that's for example 
list2 = [[15, 19, 13, 15, 30, 14, 14], [14, 22, 30, 19, 29, 17, 15], [19, 21, 11, 25, 23, 23, 30], [15, 15, 25, 18, 22, 24, 29], [24, 30, 30, 11, 25, 18, 27]]

result = [[0] * len(list2[index])  if index == 0 else list2[index] for index in list1]

print(result)

我的看法沒有任何 if 語句

list1 = [0, 1, 1, 0]
list2 = [[15, 19, 13, 15, 30, 14, 14], [14, 22, 30, 19, 29, 17, 15], [19, 21, 11, 25, 23, 23, 30], [15, 15, 25, 18, 22, 24, 29], [24, 30, 30, 11, 25, 18, 27]]

output_list = []
for index, item in enumerate(list1):
    output_list.append([element * item for element in list2[index]])
print(output_list)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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