在Python中比较三个列表
下面的代码比较了三个列表,motherList
、fatherList
和sonList
,检查sonList
中的每个值是否至少在motherList
或fatherList
中出现过一次。
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
有没有更简洁的方法来实现这个功能呢?也许可以通过递归或非递归的方式来完成。
3 个回答
0
使用列表推导式:
def compareList(motherList, fatherList, sonList):
return len([i for i in sonList if i in motherList or i in fatherList])==len(sonList)
1
你要找的是一种集合操作。Python中的集合本身就保证了所有的元素都是唯一的,你可以这样做:
child_set <= (mother_set ^ father_set)
这段代码会创建一个母集合和父集合之间的对称差集(也就是只在一个集合中存在但不在另一个集合中的所有元素),然后检查子集合中的每个元素是否都在这个对称差集中。
想了解更多,可以看看这个链接: https://docs.python.org/2/library/stdtypes.html#set-types-set-frozenset
10
使用集合吧,我的朋友。
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"
首先,这对任何开发者来说看起来都非常好,其次,它的开销不大,但这取决于数据的大小。
集合是Python中的一种特殊类型,它让你可以找到交集(哪些值在两个集合中都有)和差集,这在很多情况下都非常方便。