[英]Remove an element from nested lists with mixed structures (lists and integers) in Python
Consider the lists:考虑以下列表:
assigned = [4,8]
matching = [['B', [4, 5, 6]], ['C', [7, 8, 9]]]
I am trying to remove given integers with the following code我正在尝试使用以下代码删除给定的整数
for ii in range(len(assigned)):
while any(assigned[ii] in x for x in matching):
matching.remove(assigned[ii])
I have two problems here.我这里有两个问题。 First one is to get into the inner lists.
第一个是进入内部列表。 Right now the code does nothing because there is no matching.
现在代码什么都不做,因为没有匹配。
Second problem, I tried this:第二个问题,我试过这个:
t = ['B', [4, 5, 6]]
if any(4 in x for x in l2):
And the result was an error:结果是一个错误:
if any(4 in x for x in l2):
TypeError: 'in <string>' requires string as left operand, not int
Is there any way to achieve both in no more than two lines of code: found matching in nested lists and remove those matchings?有没有办法在不超过两行代码中实现两者:在嵌套列表中找到匹配并删除这些匹配?
Here's one way using a nested list comprehension:这是使用嵌套列表推导的一种方法:
matching = [[i[0], [j for j in i[1] if j not in assigned]] for i in matching]
print(matching)
Output: Output:
[['B', [5, 6]], ['C', [7, 9]]]
Here is another approach with list comprehension if you prefer to use .remove()
如果您更喜欢使用
.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]]]
Above is basically a list comprehension version of:上面基本上是一个列表理解版本:
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.