iT邦幫忙

0

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

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 等,但是無法寫出要的,
謝謝

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
2
ccutmis
iT邦高手 2 級 ‧ 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 檢舉

謝謝IT高手
這是我要的

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

不客氣 :D

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

補充一個,如果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)
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]
echochio iT邦高手 1 級 ‧ 2021-01-24 20:04:34 檢舉

+1

0
小偉哥
iT邦新手 4 級 ‧ 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)

我要發表回答

立即登入回答