0

## Python List 元素比對以及篩選條件

IT大大你們好

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]

### 4 個回答

2
ccutmis
iT邦高手 4 級 ‧ 2021-01-23 09:43:53

``````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]]
``````

chengwen iT邦新手 5 級 ‧ 2021-01-23 13:28:40 檢舉

ccutmis iT邦高手 4 級 ‧ 2021-01-23 13:40:24 檢舉

2
PoiBlackTea
iT邦新手 5 級 ‧ 2021-01-23 14:48:10

``````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)
``````
1
froce
iT邦大師 1 級 ‧ 2021-01-24 00:00:03

``````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]
``````
0

iT邦新手 5 級 ‧ 2021-01-24 14:02:48
• 將B裡頭的"子list"全部合起來之後，list轉set去除重複的，。
• 將setB與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)
``````