有没有办法让它更优雅?我想不出其他写这篇文章的方法了


comboList = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]
#duplicate values wont be entered into these test lists to begin with so idc about that
testList1 = [0,1,2]
testList2 = [1,2,4,7] 
testList3 = [0,2,3,6,5,69,4,6,1]
testList4 = [2,1,3] #this needs to return false
def testfunc(mainList, sublist):#This is the trash func
for list in mainList: 
y1 = 0
x1 = 0
while x1 < len(sublist):
if sublist[x1] in list:
y1 = y1 + 1
if y1 == 3:
return True
x1 = x1 + 1
return False
if testfunc(comboList,testList1):
print("Test1 Pass")
else:
print("Test1 Fail")
if testfunc(comboList,testList2):
print("Test2 Pass")
else:
print("Test2 Fail")
if testfunc(comboList,testList3):
print("Test3 Pass")
else:
print("Test3 Fail")
if testfunc(comboList,testList4):
print("Test4 Fail")
else:
print("Test4 Pass")

我对此还很陌生,我希望得到一些关于如何更优雅地编写此函数的反馈,该函数目前正按照我的意愿执行,但应该有更好的方法来执行,尤其是在python中。

您可以将逻辑分解为更短、更可读的单独函数,如以下所示:

def has_n_items(iterable, n):
""" Check whether an iterable has at least n items """
for i, _ in enumerate(iterable, 1):
if i == n:
return True
return False
def has_three_members(a, b):
""" Test whether at least three members of b are found in a """
return has_n_items((item for item in b if item in a), 3)

def test_func(a, b):
""" Test whether at least three members of list b are found in any of the sublists of list of lists a """
return any(has_three_members(b, items) for sublist in a)

为了改进您的功能,您可以这样做:


def testfunc(mainList,sublist): 
for l in mainList: 
if sum(x in l for x in sublist) == len(l):
return True
return False

它通过了测试,但如果这正是你想做的:

如果与mainList的一个列表中的值匹配,则检查sublist中的每个val。但是检查你的代码和我的代码(做同样的事情(。例如,如果您使用sublist= [0,0,0],它将返回True

任何时候在组之间测试成员身份时,都应该考虑使用sets。如果您可以控制原始输入,则应该将它们构造为集合。如果你";接收";列表,您可以随时转换它们。这对于";"大";数据对于像你这样的小例子,加速不会被注意到。

def member_test(main, test_list):
return any(len(set(sub) & set(test_list)) >= 3 for sub in main)

这使用any构造和集合交集来完成繁重的工作,并放弃了使用紧凑表示的循环。

最新更新