【问题标题】:How to find repetition of nested list if the element of list are not in order?如果列表的元素不按顺序排列,如何查找嵌套列表的重复?
【发布时间】:2020-12-18 07:28:36
【问题描述】:
#orignal list
list_one = [['a','b'],['a','c'],['b','c'],['b','a']]
li=[]
for i in list_one:
    for j in list_one:
        if i[0] == j[1] and j[0] == i[1]:
            li.append([i,j])
print(li)

#[[['a', 'b'], ['b', 'a']], [['b', 'a'], ['a', 'b']]]

我只需要输出 [a,b] a 和 b 可以根据条件而变化,例如 a 可以是苹果或任何东西

【问题讨论】:

  • 这能回答你的问题吗? finding duplicates in a list of lists
  • @CarloZanocco "...如果列表的元素不按顺序"
  • @ThierryLathuille 为什么不订购呢?他没有提出不排序列表的约束问题。他只是说他们不按顺序。
  • @CarloZanocco 我在您建议的副本中没有看到任何可以回答这个问题的答案...
  • 考虑到@ThierryLathuille 也许你想保留列表的顺序,所以检查here

标签: python python-3.x for-loop nested-lists


【解决方案1】:

在考虑子列表时,只需要在当前子列表之外的列表队列中查找重复项即可。对您的代码稍作改动,您可以这样做:

list_one = [['a','b'],['a','c'],['b','c'],['b','a']]
li=[]
for index, i in enumerate(list_one):
    for index2 in range(index+1, len(list_one)):
        j = list_one[index2]                
        if i[0] == j[1] and j[0] == i[1]:
            li.append([i,j])
print(li)
# [[['a', 'b'], ['b', 'a']]]

【讨论】:

    【解决方案2】:

    您似乎正在寻找包含以前从未见过的字母的项目。最简单的方法是构建缓存。

    cache = set() # will contain all individual letters that have been seen
    li = []
    for item in list_one:
        if not any(letter in cache for letter in item):
            li.append(item)
        cache.update([letter for letter in item])
    print(li)
    
    [['a', 'b']]
    

    【讨论】:

      【解决方案3】:

      一种方法可能是:

      对列表进行排序,找到嵌套的重复项。

      #orignal list
      data = [['a','b'],['a','c'],['b','c'],['b','a']]
      seen = []
      data = [sorted(x) for x in data]
      data = [x if x in seen else seen.append(x) for x in data]
      print([x for x in data if x])
      

      输出:

      [['a', 'b']]
      

      【讨论】:

        猜你喜欢
        • 2019-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-10
        • 1970-01-01
        • 2020-09-08
        • 1970-01-01
        相关资源
        最近更新 更多