用Python比较3个列表

2024-10-03 09:13:38 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的代码比较了三个列表motherList fatherlistsonList,检查{}中的每个值是否以motherList或{}表示一次。在

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)

输出:

^{pr2}$

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


Tags: and代码in列表forifdefcount
3条回答

使用列表理解:

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

用套,我的朋友。在

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

所以你的代码看起来像:

^{pr2}$

首先,它看起来真的很适合任何开发人员,其次它不是那么昂贵,但取决于数据大小。在

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

你要找的是一个固定操作。Python集合已经强制要求所有项目都是唯一的,您可以执行以下操作:

child_set <= (mother_set ^ father_set)

在这两个集合中,父项和子项在集合中是对称的,但不是所有子项集合的差异。在

进一步阅读:https://docs.python.org/2/library/stdtypes.html#set-types-set-frozenset

相关问题 更多 >