我希望它搜索整個 list1 和子串列以確保 first_word 確實在其中一個,然后我希望它確保 second_word 尚未分配給 list_1 中的一個串列。最后,我希望它將 second_word 附加到 list_1 中包含 first_word 的串列中
list_1= [['test1', 'test2'],["test3"],["test4", "test5"],["test6"],["test7"]]
list_2= ['123','234', '345','435','654']
first_word= test1
second_word = test6
for i in list_1:
if second_word in i:
print(second_word , "already assigned")
break
elif first_word not in i:
print(first_word, "is not in list")
break
else:
index = list_1.index((i))
list_1[index].append(second_word)
print(list_1)
break
所有這些陳述句都可以自己進行,但我似乎無法讓它們一起作業。
我的意思是,如果 list_1 中不存在 first_word 或者如果 second_word 已經在串列中,它將不會附加。
uj5u.com熱心網友回復:
這將迭代 list_1 的每個專案
- 檢查每個專案中的 first_word 是否
- 如果 first_word 在專案中
- 檢查 second_word 是否在任何 list_1 專案中
- 如果 second_word 不在任何 list_1 項中
- 將 second_word 附加到專案 first_word 被發現于
list_1= [['test1', 'test2'],["test3"],["test4", "test5"],["test6"],["test7"]]
list_2= ['123','234', '345','435','654']
first_word = 'test1'
second_word = 'test11'
for i in list_1:
if first_word in i and not any([second_word in i for i in list_1]):
i.append(second_word)
print(list_1)
回傳:
[['test1', 'test2', 'test11'], ['test3'], ['test4', 'test5'], ['test6'], ['test7']]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/517981.html
