我有两个字符串列表:
list1 = ["python", "java", "perl", "sql"]
list2 = [ "scala", "python", "perl"]
我需要一个差异列表,如:
difference = ["java", "sql", "scala"]
我试过了:
def stringDifference(list1, list2):
difference = []
for i in list1:
if i not in list2:
difference.append(i)
for i in list2:
if i not in list1:
difference.append(i)
print difference
但我只是想看看是否有比Python版本少于3的解决方案有效的方法。
答案 0 :(得分:2)
您可以添加两个列表推导的结果
>>> list1 = ["python", "java", "perl", "sql"]
>>> list2 = [ "scala", "python", "perl"]
>>> [i for i in list1 if i not in list2] + [i for i in list2 if i not in list1]
['java', 'sql', 'scala']
答案 1 :(得分:1)
虽然您可以按原样保留列表,但可以更快地将它们全部转换为字典,这样可以像集合那样快速进行成员资格测试:
list1 = ["python", "java", "perl", "sql"]
list2 = [ "scala", "python", "perl"]
d1 = dict.fromkeys(list1)
d2 = dict.fromkeys(list2)
difference = [i for i in d1 if i not in d2] + [i for i in d2 if i not in d1]
print difference
答案 2 :(得分:0)
使用collections.Counter
:
>>> from collections import Counter
>>> list1 = ["python", "java", "perl", "sql"]
>>> list2 = [ "scala", "python", "perl"]
>>> [ x for x,y in Counter(list1+list2).items() if y==1 ]
['sql', 'java', 'scala']
使用count:
>>> my_list = list1+list2
>>> [ x for x in my_list if my_list.count(x)==1 ]
['java', 'sql', 'scala']
设置更好,但你问:
>>> [x for x in list1 if x not in list2 ]+ [ x for x in list2 if x not in list1]
['java', 'sql', 'scala']