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 中。
uj5u.com熱心網友回復:
您可以將邏輯分解為更短且更具可讀性的單獨函式,如下所示:
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)
uj5u.com熱心網友回復:
除了改進您的功能外,您還可以簡化測驗以避免重復:
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
testlists = {'test1': [0,1,2], 'test2': [1,2,4,7], 'test3': [0,2,3,6,5,69,4,6,1], 'test4': [2,1,3]}
def testfunc(mainList, sublist):
for mylist in mainList:
count = 0
for item in sublist:
if item in mylist:
count = 1
if count == 3:
return True
return False
for name, test in testlists.items():
if testfunc(comboList, test):
print(name, ' Passed')
else:
print(name, ' Failed')
uj5u.com熱心網友回復:
為了改善您的功能,您可以這樣做:
def testfunc(mainList,sublist):
for l in mainList:
if sum(x in l for x in sublist) == len(l):
return True
return False
它通過了測驗,但如果這正是你想要做的,那就不知道:
檢查每個 valsublist是否與一個串列中的值匹配mainList。但是檢查你的代碼和我的代碼(做同樣的事情)。True例如,如果您使用assublist= [0,0,0]
uj5u.com熱心網友回復:
每當您在組之間測驗成員資格時,您都應該考慮使用sets. 如果您可以控制原始輸入,則應將它們構造為集合。如果您“接收”串列,您可以即時轉換它們。對于“大”資料,這將是銀河系更快。對于像你這樣的小例子,加速不會被注意到。
def member_test(main, test_list):
return any(len(set(sub) & set(test_list)) >= 3 for sub in main)
這使用any構造和集合交集來完成繁重的作業,并以緊湊的表示形式放棄回圈。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/525165.html
