IT大大你們好
想詢問當我有兩組List元素,想互相比較並取出符合條件的,要如何寫呢?
EX:
A=[1,2,3,4,5],[3,4,5,7,8],[10,20,45,50,51]
B=[3,5],[2,3],[3,4],[10,50],[4,5],[7,8]
B元素要跟A比較,如果比較結果有超過三組元素,則取出A該中括弧元素
預期得到
A=[1,2,3,4,5],[3,4,5,7,8]
有試過set、compare 等,但是無法寫出要的,
謝謝
高深簡潔的語法我不會,這裡提供一個土法煉鋼的方法 : 用多層迴圈來處理。
多層迴圈在學校教學裡很常見的是寫九九乘法表,這就是個類似的應用,以下是範例:
A=[1,2,3,4,5],[3,4,5,7,8],[10,20,45,50,51]
B=[3,5],[2,3],[3,4],[10,50],[4,5],[7,8]
result=[]
for i in A:
totla_match_num=0
for j in B:
match_len=0
for k in j:
if k in i:
match_len=match_len+1
if match_len==len(j):
totla_match_num=totla_match_num+1
if totla_match_num>3:
result.append(i)
print(result)
執行結果:
[[1, 2, 3, 4, 5], [3, 4, 5, 7, 8]]
只要你邏輯清晰條件定義明確,用最基本的迴圈加條件判斷就能解決許多問題。
補充一個,如果List內元素不重複可以用的方法
A = [1,2,3,4,5],[3,4,5,7,8],[10,20,45,50,51]
B = [3,5],[2,3],[3,4],[10,50],[4,5],[7,8]
result = []
for i in A:
count = 0
for j in B:
if set(j).issubset(i):
if (count := count+1) > 3:
result.append(i)
break
print(result)
好孩子不要學的拚最短行數訓練。
A = [1,2,3,4,5],[3,4,5,7,8],[10,20,45,50,51]
B = [3,5],[2,3],[3,4],[10,50],[4,5],[7,8]
def countLstIn(allIn, outer):
return sum(tuple(all([e in outer for e in i]) for i in allIn))
result = [a for a in A if countLstIn(B, a) >= 3]
# _*_ coding:utf-8 _*_
A=[1,2,3,4,5],[3,4,5,7,8],[10,20,45,50,51]
B=[3,5],[2,3],[3,4],[10,50],[4,5],[7,8]
listB = [element for subB in B for element in subB]
setB = set(listB)
print('setB=', setB)
result = []
for data in A:
data = set(data)
tmp = setB.intersection(data)
if(len(tmp)>3):
result.append(list(data))
print(result)