【问题标题】:python list of lists common elements iterationpython list of list 常见元素迭代
【发布时间】:2020-02-04 07:06:31
【问题描述】:
list= [[5, 4, 6], [6, 4, 5], [7, 1, 2]]

我有上面的列表,我想比较每个列表索引,如 [5,4,6][6,4,5][7,1,2],即与所有其他列表索引

和输出:如果比较中两个索引之间存在任何共同元素,那么我想以一种格式输出 “每个索引的第一个元素”以及索引中的任何常见元素。

此迭代的答案是 [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 个列表索引有任何共同点,我想获得一个新的输出列表,其中包含列表索引和公共元素的第一个元素

final output= [[5,6,4],[6,5,4],[7]]

【问题讨论】:

  • 你能展示一下你到目前为止所做的尝试吗?如果它不起作用也没关系。
  • 也许你应该从一个不太复杂的任务开始。如果您不了解基础知识,那么您不想从这样的事情开始。

标签: python python-2.7 list arraylist


【解决方案1】:
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)

【讨论】:

  • 感谢您抽出宝贵时间回答,我真的很感谢第 15 行:TypeError: 'list' object is not callable
  • 当我运行你的答案时,我收到错误 TypeError: 'list' object is not callable on line 10
  • @sudiksha 尝试用inCommon = set(firstList).intersection(secondList)替换inCommon = list(set(firstList).intersection(secondList))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-02-11
  • 2020-04-18
  • 1970-01-01
  • 2021-06-22
  • 1970-01-01
  • 2011-02-10
  • 2013-04-27
相关资源
最近更新 更多