python - 不使用 SET 的两个字符串列表之间的区别

标签 python algorithm python-2.7

我有两个字符串列表:

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

但我只是想看看在低于3的Python版本中是否有比这个解决方案更有效的方法。

最佳答案

您可以添加两个列表理解的结果

>>> 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']

关于python - 不使用 SET 的两个字符串列表之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27305712/

相关文章:

python - Pygame 速度和碰撞问题

python - 无法将数据帧列转换为 24 小时格式日期时间

c++ - 返回列表子集的最佳方法是什么

arrays - 给定一个数字 X ,在两个排序数组中找到两个元素,例如 A[i]+B[j] = X in O(n+m)

algorithm - 在 O(nlogn) 中找到与一条线距离相同的所有点对

python - 合并两个 PDF

python - 使用 python 点击​​ http url 获取 IOError

python - 如何在 Pycharm 中运行 Scrapy 单元测试

python - 从现有的阻塞代码重构扭曲的 tcp 客户端

python - 在 Pandas 图中仅隐藏轴标签,而不是整个轴