我是一個 python 新手,我想檢查每個串列元素是否存在于另一個串列中(同時尊重索引)并將這個元素附加到第三個串列中。像這樣。如果 'listy'("11-02-jeej") 的第一個元素包含 list_of_dates ("11-02) 的第一個元素,我希望將這個元素 "11-02-jeej" 附加到串列的第一個串列中串列。下面的代碼對我不起作用:(
the output that i want from this code is :[["11-02-jeej"], [2apples], []]
but instead i get : [[], [], []]
太感謝了 !
list_of_dates =["11-02,", "2", "5"]
listy = ["11-02-jeej", "2apples", "d44"]
length = len(list_of_dates)
lst = [[] for m in range(length)]
for i in range(len(list_of_dates)):
date = list_of_dates[i]
for j in range(len(listy)):
name = listy [j]
if date in name:
lst[m].append(name)
print(lst)
uj5u.com熱心網友回復:
您的代碼中存在以下問題:
輸入的第一個字串中有一個逗號:“11-02”。正如您所期望的那樣,這是一個前綴,我想后面的逗號不應該在那里:“11-02”
該
if陳述句應該在內部回圈內,因為它需要在name那里分配的變數。m不是正確的索引。它應該是i,所以你得到:lst[i].append(name)
所以這是您的代碼,其中包含這些更正:
list_of_dates =["11-02", "2", "5"]
listy = ["11-02-jeej", "2apples", "d44"]
length = len(list_of_dates)
lst = [[] for m in range(length)]
for i in range(len(list_of_dates)):
date = list_of_dates[i]
for j in range(len(listy)):
name = listy [j]
if date in name:
lst[i].append(name)
print(lst)
請注意,這些回圈可以用串列推導式撰寫:
lst = [[s for s in listy if prefix in s] for prefix in list_of_dates]
請注意,對于給定的示例,“2”也出現在“11-02-jeej”中,因此“11-02”和“2”都給出了匹配項,這會影響結果。如果您希望“2”僅與“2apples”匹配,那么您可能希望僅在字串開頭測驗匹配,使用.startswith().
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/478279.html
