![](/img/trans.png)
[英]Is there a better way to compare two lists in Python, stopping at the shorter list?
[英]Compare two python lists and expand the shorter list to the length of the longer list
我的問題標題有點混亂,我只是不確定標題是否能很好地解釋它。
我有兩個清單。
list_1 = [10,20,30,40,50,60,70,80,90]
list_2 = [10,40,70]
預期產量:
new_list = [10,0,0,40,0,0,70,0,0]
我應該怎么做? 以下是我所擁有的,但我不確定是哪里出了問題:
def expand_list(complete_list, to_be_expand_list):
expanded_list = []
for i in complete_list:
for j in to_be_expand_list:
if i == j:
expanded_list.append(j)
else:
if expanded_list[-1] != 0:
expanded_list.append(0)
return expanded_list
嘗試這樣的事情:
def expand_list(full_list, short_list):
return [x if x in short_list else 0 for x in full_list]
這使用列表推導來生成列表,該列表是完整列表的長度,但僅包含短列表中的那些元素,所有其余元素都用零代替。
list_1 = [10,20,30,40,50,60,70,80,90]
list_2 = [10,40,70]
new_list = list_1[:]
for i, v in enumerate(list_1):
if v not in list_2:
new_list[i] = 0
print new_list
結果:
[10, 0, 0, 40, 0, 0, 70, 0, 0]
這將檢查list_1中不在list_2中的位置,並將其設置為0
你將會在所有to_be_expand_list
每個項目上complete_list
和(幾乎)你追加的項目每次迭代,所以在最后你會len(list1)*len(list2)
項目。
您應該將其更改為:
def expand_list(complete_list, to_be_expand_list):
expanded_list = []
for i in complete_list:
if i in be_expand_list:
expanded_list.append(i)
else:
expanded_list.append(0)
return expanded_list
如果您尋找更簡單的方法,則可以使用列表理解 :
[x if x in list2 else 0 for x in list1]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.