我有两个清单:
l1 = [[1,2,3,4,5], [1,2,4,6,7]]
l2 = [[1,2,3,4,5], [1,2,4,6,7], [1,2,3,6,8], [1,2,3,0,9], [1,2,6,7,6]]
我想创建一个新列表l3
,其中包含不在l2
中的l1
项。像这样:
l3 = l2-l1
所以,我期待l3
为:
l3 = [[1,2,3,6,8], [1,2,3,0,9], [1,2,6,7,6]]
我怎样才能实现这一目标? 任何解决方案在python中使用remove()或delete()??
答案 0 :(得分:1)
只是做:
l3 = [lst for lst in l2 if lst not in l1]
答案 1 :(得分:1)
为O(1)成员资格测试构建一组元组。 (在你琐碎的例子中,这不是必要的,但我假设大的列表。)然后通过列表理解进行过滤。
>>> checker = set(map(tuple, l1))
>>> [l for l in l2 if tuple(l) not in checker]
[[1, 2, 3, 6, 8], [1, 2, 3, 0, 9], [1, 2, 6, 7, 6]]
答案 2 :(得分:0)
使用以下代码:
l1 = [[1,2,3,4,5], [1,2,4,6,7]]
l2 = [[1,2,3,4,5], [1,2,4,6,7], [1,2,3,6,8], [1,2,3,0,9], [1,2,6,7,6]]
l3=[]
for i in l2:
if i not in l1:
l3.append(i)
答案 3 :(得分:0)
如果您要删除l2
中的l1
个子列表并使用剩余的子列表创建新列表,请尝试以下操作:
l1 = [[1,2,3,4,5], [1,2,4,6,7]]
l2 = [[1,2,3,4,5], [1,2,4,6,7], [1,2,3,6,8], [1,2,3,0,9], [1,2,6,7,6]]
for sub in l1:
if sub in l2:
l2.remove(sub)
l3 = l2[:]
>>> l1
[[1, 2, 3, 4, 5], [1, 2, 4, 6, 7]]
>>> l2
[[1, 2, 3, 6, 8], [1, 2, 3, 0, 9], [1, 2, 6, 7, 6]]
>>> l3
[[1, 2, 3, 6, 8], [1, 2, 3, 0, 9], [1, 2, 6, 7, 6]]
答案 4 :(得分:0)
使用Itertool:
curl -s http://198.51.100.1:63053/v1/records | grep mariadb-galera
itertools为这类问题提供了最快速,最强大的解决方案,并且在列表大小增加时,时间效率会很高,
这是实现解决方案的pythonic方式,俗话说"当你在罗马时,喜欢罗马人。"
答案 5 :(得分:0)
如果订单和类型不重要,请改用sets。它们很快并且类似于你的例子:
set1 = {tuple(l) for l in l1}
set2 = {tuple(l) for l in l2}
set2 - set1
# {(1, 2, 3, 0, 9), (1, 2, 3, 6, 8), (1, 2, 6, 7, 6)}
前两行将列表转换为(无序)元组集,例如:
{(1, 2, 4, 6, 7), (1, 2, 3, 4, 5)}
{(1, 2, 4, 6, 7), (1, 2, 3, 4, 5), (1, 2, 3, 0, 9), (1, 2, 3, 6, 8), (1, 2, 6, 7, 6)}
这些表单允许设置操作,即相当于set2
和set1
之间差异的操作。
答案 6 :(得分:0)
>>> l1 = [[1,2,3,4,5],[1,2,4,6,7]]
>>> l2 = [[1,2,3,4,5],[1,2,4,6,7],[1,2,3,6,8],[1,2,3,0,9],[1,2,6,7,6]]
>>> for i in l1:
>>> if i in l2:
>>> del l2[l2.index(i)]
>>> print(l2)