我想删除python中的元组列表。我有清单
l = [('name','sam'),('age', 20),('sex', 'male')]
和另一个元组列表
r = [('name','sam'),('age', 20)]
我正在尝试删除r
和l
两者中的元素。我这样做:
for item in l:
if item in r:
del item
但元素并未删除。输出什么都没有,当我打印修改后的列表时:
>>> l
然后原始列表正在打印。
[('name','sam'),('age', 20),('sex', 'male')]
请帮帮我,如何删除元组列表中的元素。
答案 0 :(得分:3)
您可以对两个列表进行转换并减去它们:
l = [('name','sam'),('age', 20),('sex', 'male')]
r = [('name','sam'),('age', 20)]
以下行只会返回l
但不在r
中的元素:
set(l) - set(r)
答案 1 :(得分:0)
您可以使用filter()
。
for item in filter(lambda x: x not in r, l):
# You can use your items here
# The list gets out of scope, so if there are no other references,
# the garbage collector will destroy it anyway
或者,如果您还需要在其他地方使用该列表,您也可以考虑使用列表解析来创建新列表:
l = [i for i in l if i not in r]
答案 2 :(得分:0)
这将返回l中的项目列表,而不是r。
此解决方案与减去集合的解决方案之间的区别在于,如果列表中有重复项,则不会丢失信息。您使用子集
丢失此信息difference = [item for item in l if item not in r]
答案 3 :(得分:0)
有很多方法可以解决这个问题:
按l and r
查找这些列表的AND以查找两者中常见的列表,然后用这样的方式操作:[x for x in l if x not in l and r ]
。这将比上述答案更有效率。
在某些情况下,如果len(l) < len(r)
会出现正确的标记答案。所以简单地克服这个问题
list=[]
p = l and r
list.extend([ [x for x in l if x not in p ], [x for x in r if x not in p ]])
希望它会淡化一些揭露。