【问题标题】:How to compare particular element in list python3?如何比较列表python3中的特定元素?
【发布时间】:2021-01-27 09:36:36
【问题描述】:
    l1= [['1', 'apple', '1', '2', '1', '0', '0', '0'], ['1', 
              'cherry', '1', '1', '1', '0', '0', '0']]
    
    l2 = [['1', 'cherry', '2', '1'], 
    ['1', 'plums', '2', '15'], 
    ['1', 'orange', '2', '15'], 
    ['1', 'cherry', '2', '1'], 
    ['1', 'cherry', '2', '1']]
    output = []
    for i in l1:
        for j in l2:
            if i[1] != j[1]:
                output.append(j)
        break
    print(output)
    
    Expected Output:
        [['1', 'plums', '2', '15'], ['1', 'orange', '2', '15']]

如何停止迭代并找到唯一元素并获取子列表? 如何停止迭代并找到唯一元素并获取子列表?

【问题讨论】:

  • 你想要 l2 中没有 l1 的元素?
  • 是的,只需要 l2 @Mike67

标签: python-3.x loops for-loop iteration break


【解决方案1】:

根据水果名称查找L2中不在L1中的元素:

l1= [[1,'apple',3],[1,'cherry',4]]
l2 = [[1,'apple',3],[1,'plums',4],[1,'orange',3],[1,'apple',4]]
output = []
for e in l2:
   if not e[1] in [f[1] for f in l1]:  # search by matching fruit
       output.append(e)

print(output)

输出

[[1, 'plums', 4], [1, 'orange', 3]]

【讨论】:

    【解决方案2】:

    您可以将来自list1 的所有唯一元素存储在一个新列表中,然后检查list2 是否存在于new list 中。比如:

    newlist = []
    for item in l1:
        if item[1] not in newlist:
            newlist.append(item)
    output = []
    for item in l2:
        if item[1] not in newlist:
            output.append(item)
    print(output)
    

    这有点低效,但很容易理解。

    【讨论】:

      猜你喜欢
      • 2018-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-12
      • 2015-09-30
      相关资源
      最近更新 更多