[英]Remove an element from nested lists with mixed structures (lists and integers) in Python
考慮以下列表:
assigned = [4,8]
matching = [['B', [4, 5, 6]], ['C', [7, 8, 9]]]
我正在嘗試使用以下代碼刪除給定的整數
for ii in range(len(assigned)):
while any(assigned[ii] in x for x in matching):
matching.remove(assigned[ii])
我這里有兩個問題。 第一個是進入內部列表。 現在代碼什么都不做,因為沒有匹配。
第二個問題,我試過這個:
t = ['B', [4, 5, 6]]
if any(4 in x for x in l2):
結果是一個錯誤:
if any(4 in x for x in l2):
TypeError: 'in <string>' requires string as left operand, not int
有沒有辦法在不超過兩行代碼中實現兩者:在嵌套列表中找到匹配並刪除這些匹配?
這是使用嵌套列表推導的一種方法:
matching = [[i[0], [j for j in i[1] if j not in assigned]] for i in matching]
print(matching)
Output:
[['B', [5, 6]], ['C', [7, 9]]]
如果您更喜歡使用.remove()
,這是另一種使用列表理解的方法
assigned = [4,8]
matching = [['B', [4, 5, 6]], ['C', [7, 8, 9]]]
[item[1].remove(x) for item in matching for x in item[1] if x in assigned]
print(matching)
# [['B', [5, 6]], ['C', [7, 9]]]
上面基本上是一個列表理解版本:
for item in matching:
for x in item[1]:
if x in assigned:
item[1].remove(x)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.