我有两个列表,例如:
a = ['hello','world']
b = ['hello','world','im','steve']
如果我想创建一个第三个列表,仅包含不在两个列表中的元素:
c = ['im','steve']
如果元素的顺序很重要,我该怎么办?我知道可以使用集合,但它们会打乱我的列表顺序。我可以使用
' '.join(list)
将它们转换为字符串,但不确定如何在该格式中执行此操作。我有两个列表,例如:
a = ['hello','world']
b = ['hello','world','im','steve']
c = ['im','steve']
' '.join(list)
将它们转换为字符串,但不确定如何在该格式中执行此操作。您可以连接列表并使用列表推导式:
a = ['hello','world']
b = ['hello','world','im','steve']
final_vals = [i for i in a+b if i not in a or i not in b]
输出:
['im', 'steve']
选项1:使用set方法(推荐)
集合有一个symmetric_difference
方法,该方法仅返回来自a
或b
的元素。可以通过列表推导式将a + b
连接成一个列表来保留顺序。
comp = set(a).symmetric_difference(b)
[x for x in a + b if x in comp]
# ['im', 'steve']
选项2: pathlib
方法
供参考,另一种比较两个列表的方法可能是使用 pathlib.Path.relative_to
方法:
import pathlib
p = pathlib.Path(*b)
r = p.relative_to(*a)
list(r.parts)
# ['im', 'steve']
注意:b
是更长的列表。此选项可能比简单的列表推导式效率低。set(a).symmetric_difference(b)
,否则这个过程会变得很慢。 - Jean-François Fabrec = a + b
for v in set(a).intersection(set(b)):
while v in c:
c.remove(v)
a=[1, 1, 2, 3] ; b=[1, 2]
将返回 c=[3, 1]
。 - viraptorl2
中不存在的元素,然后将参数反转后调用该函数两次:a = ['hello','world', 'foo']
b = ['hello','world','im','steve']
def difference(l1, l2):
return list(filter(lambda x: x not in l2, l1))
print(difference(a, b) + difference(b, a))
# ['foo', 'im', 'steve']
filter()
,一个简单的列表解析也可以起到同样的作用:[item for item in l1 if item not in l2]
a = ['hello','world']
b = ['hello','world','im','steve']
a = set(a)
b = set(b)
print(a.symmetric_difference(b))
a = ['hello', 'world']
b = ['hello', 'world', 'im', 'steve']
min_list = a if len(a) < len(b) else b
max_list = b if len(b) > len(a) else a
results = []
for i, item in enumerate(min_list):
# Iterate through the shortest list to avoid IndexError(s)
if min_list[i] != max_list[i]:
results.append(min_list[i])
results.append(max_list[i])
results.extend(max_list[i + 1:])
print(results)
# Prints: ['im', 'steve']
results
列表中,这意味着对于以下输入:a = ['hello', 'foo']
b = ['hello', 'world', 'im', 'steve']
>>> ['foo', 'world', 'im', 'steve']
zip
,则无需检查列表的大小,还可以使用 max
选择最长的列表,或者使用 sorted
同时完成两个操作。 - Copperfield使用标准的 for
循环来检查列表中不存在于其中一个列表中的项目(可能比列表推导更易懂):
a = ['hello','world', 'foo']
b = ['hello','world','im','steve']
c = a+b
ans = []
for i in c:
if i not in a or i not in b:
ans.append(i)
print(ans)
输出:
['foo', 'im', 'steve']
我建议使用集合的^
运算符,例如set(a) ^ set(b)
。示例(演示):
>>> a = ['hello','world']
>>> b = ['hello','world','im','steve']
>>> set(a) ^ set(b)
{'steve', 'im'}
>>> sorted(set(a) ^ set(b),key=max([a,b],key=len).index)
['im', 'steve']
>>>
https://docs.python.org/2/library/stdtypes.html#frozenset.symmetric_difference
a
是例如['hello', 'the', 'world']
或['world', 'hello']
时,你该怎么办?如果它是['world', 'hello', 'world']
呢?如果其中包含'steve'
,那么它出现的位置是否重要? - torek