簡體   English   中英

python 列表常見元素迭代列表

[英]python list of lists common elements iteration

list= [[5, 4, 6], [6, 4, 5], [7, 1, 2]]

我有上面的列表,我想將[5,4,6]之類的每個列表索引與[6,4,5][7,1,2]即每個其他列表索引進行比較

對於 output:如果在比較中 2 個索引之間存在任何共同元素,那么我希望 output 格式為“每個索引的第一個元素”以及索引中的任何共同元素。

此迭代的答案將是 [5,4,6],因為 5 是比較索引的第一個元素,6 是比較索引的第一個元素,4 是公共元素。

接下來將[6, 4, 5][5,4,6 ] 和[7,1,2]進行比較,答案將是 [6,5,4]

接下來將[7,1,2][5,4,6][6, 4, 5]進行比較,答案將是[7]

請幫忙,我已經嘗試了很長時間。

基本上我希望每個列表索引與其他所有列表索引檢查公共元素,如果 2 個列表索引有任何共同點,我想獲得一個新的 output 列表,其中包含列表索引和公共元素的第一個元素

final output= [[5,6,4],[6,5,4],[7]]
myL = [[5, 4, 6], [6, 4, 5], [7, 1, 2]]
newLi = []

for i in range(len(myL)):  
  tmpLi = []
  firstList = myL[i]
  for a in range(len(myL)):
    if a != i:
      secondList = myL[a]
      inCommon = set(firstList).intersection(secondList)
      if len(inCommon) != 0:
        tmpLi.append(firstList[0])
        tmpLi.append(secondList[0])
        for b in inCommon:
          if b not in tmpLi:
            tmpLi.append(b)
  if len(tmpLi) == 0:
    tmpLi.append(firstList[0])
  newLi.append(tmpLi)
print(newLi)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM