【发布时间】:2014-06-18 14:53:56
【问题描述】:
以下代码比较三个列表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
有没有更简洁的方法来实现这一点? 也许通过递归或非递归方式
【问题讨论】:
-
由于您的问题是关于代码改进并涉及工作代码,您可能在 Code Review 上运气更好,但请务必查看 site's help center 以确保您的问题是适当的
-
你的意思是一次或多次还是完全一次?
-
@Padraic Cunningham 至少一次
-
井套绝对是要走的路。您应该查看文档,其中有像
set.symmetric_difference这样的方法可以将任何可迭代作为参数,因此您不必从所有列表中创建集合。使用^ &等必须先将所有转换为集合。 -
这个问题似乎是题外话,因为它是关于改进工作代码,它可能更适合 codereview.stackexchange.com