![](/img/trans.png)
[英]Remove a sublist from a list in which the numbers alreadys exist in another sublist
[英]Remove element from sublist according to another list
我有一个充满子列表的列表:
a = [['12345/0111','57894/0311','45698/2333'],['12345/0600','87456/1234']]
然后我有另一个清单:
b = ['0111','0600','0311']
我想删除列表a中不包含列表b 中的元素的所有元素。 我认为b 中的 firts 元素应该是这样的(在本例中为 45698/2333 和 87456/1234):
for x in a:
for y in x:
if b[0] not in y:
x.remove(y)
但它甚至对第一个元素也不起作用,我真的不知道如何对b 中的所有元素执行此操作。
编辑:对不起,我没有在输出中指定我需要具有相同的嵌套列表结构。
试试这个:
# create a new list to store values
c = []
for x in a:
for y in x:
if str.split(y, '/')[1] in b:
c.append(y)
我的结果:
a
[['12345/0111', '57894/0311', '45698/2333'], ['12345/0600', '87456/1234']]
b
['0111', '0600', '0311']
c = []
for x in a:
for y in x:
if str.split(y, '/')[1] in b:
c.append(y)
c
['12345/0111', '57894/0311', '12345/0600']
OP 澄清后编辑:
for x in a:
for y in x:
if str.split(y, '/')[1] in b:
x.remove(y)
编辑结果:
for x in a:
for y in x:
if str.split(y, '/')[1] in b:
x.remove(y)
a
[['57894/0311', '45698/2333'], ['87456/1234']]
您是说要删除 b 中的任何内容,这似乎不是您的意思。 在任何情况下,如果您从以下两个示例中的任何一个中删除“not”,它们都会为您提供 b 中的那些。
a = [['12345/0111','57894/0311','45698/2333'],['12345/0600','87456/1234']]
b = ['0111','0600','0311']
output = []
for l in a:
for e in l:
if not any([x in e for x in b]):
output.append(e)
output = []
for l in a:
output.append([x for x in l if not any(z in x for z in b)])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.