【问题标题】:Comparing 3 lists in Python比较 Python 中的 3 个列表
【发布时间】:2014-06-18 14:53:56
【问题描述】:

以下代码比较三个列表motherList fatherlistsonList,检查sonList 中的每个值是否在motherListfatherList 中表示一次。

def compareList(motherList, fatherList, sonList):
    count = 0
    for x in sonList:
            if x in motherList and x in fatherList:
                    count = 2
            elif x in motherList or x in fatherList:
                    count += 1
    if count >= 2:
            ans = "Mendelion"
    else:
            ans = "Non-Medelian"

    print"{0} {1} \t {2} \t {3}".format(motherList, fatherList, sonList, ans)

输出:

['0']        ['0']         ['4']         Non-Mendelion
['2', '6']   ['0']         ['0', '2']    Mendelion
['1']        ['0']         ['1']         Non-Medelian
['-1', '2']  ['-4', '-1']  ['-4', '2']   Mendelion

有没有更简洁的方法来实现这一点? 也许通过递归或非递归方式

【问题讨论】:

  • 由于您的问题是关于代码改进并涉及工作代码,您可能在 Code Review 上运气更好,但请务必查看 site's help center 以确保您的问题是适当的
  • 你的意思是一次或多次还是完全一次?
  • @Padraic Cunningham 至少一次
  • 井套绝对是要走的路。您应该查看文档,其中有像 set.symmetric_difference 这样的方法可以将任何可迭代作为参数,因此您不必从所有列表中创建集合。使用^ & 等必须先将所有转换为集合。
  • 这个问题似乎是题外话,因为它是关于改进工作代码,它可能更适合 codereview.stackexchange.com

标签: python list compare


【解决方案1】:

使用集合,我的朋友。

In [1]: {0, 1, 2} & {1, 2, 3} & {2, 3, 4}
Out[1]: set([2])

所以您的代码将如下所示:

if set(motherList) & set(fatherlist) & set(sonList):
    ans = "Mendelion"
else:
    ans = "Non-Medelian"

首先,它看起来对任何开发人员都非常非常好,其次它并不昂贵,但取决于数据大小。

Sets 是 python 中的一种特殊类型,它使您能够找到交集(两个集合中都有哪些值)和差异,这在多对多情况下使用非常方便。

【讨论】:

    【解决方案2】:

    使用列表推导:

    def compareList(motherList, fatherList, sonList):
        return len([i for i in sonList if i in motherList or i in fatherList])==len(sonList)
    

    【讨论】:

      【解决方案3】:

      您正在寻找的是集合操作。 Python 集已经强制要求所有项目都是唯一的,您可以这样做:

      child_set <= (mother_set ^ father_set)
      

      它创建了一组母亲和父亲集之间的对称差异(所有项目都在一个或另一个但不是两者),然后测试子集中的每个项目都在该集合中。

      延伸阅读:https://docs.python.org/2/library/stdtypes.html#set-types-set-frozenset

      【讨论】:

        猜你喜欢
        • 2021-10-20
        • 1970-01-01
        • 2018-03-19
        • 2015-03-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多