在某些元素上打破循环

2024-05-08 16:09:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个列表,每个都有[[product,rate,volume], [product,rate,volume], ...]。使用下面的框架,有没有一种方法可以在循环遍历产品之后中断循环?所以循环在遍历rate和volume之前就停止了

for currentproduct, rate, volume in volumedifferencearray:
    for product, rates, volumes in cleanlist:
        if currentproduct == product:
            volumediff = volumes - volume
            volumedifference.append([currentproduct, rates, volumediff])

Tags: 方法in框架列表forrate产品product
1条回答
网友
1楼 · 发布于 2024-05-08 16:09:03

假设两个列表(比如list1和list2)中的产品相同,并且希望第三个列表(比如list3)中的产品数量不同:

list1.sort() # sorts on first column, i.e., product
list2.sort() # same for clean list

list3 = [ [x[0],y[1],y[2]-2[2]] for x,y in zip(list1,list2) ]

zip(list1, list2)帮助我们同时迭代两个列表。 xy是对应的元素list1list2。看看你问题中的代码,我的理解是你想要一个列表,其中第一列是产品,第二列是价格(来自cleanlist),第三列是体积的差异

所以

  1. x[0]给出产品
  2. y[1]给出干净列表中的速率
  3. y[2]-x[2]给出了体积上的差异

示例:

list1 = [[1, 2, 3], [2, 1, 0], [3, 0, 1]]
list2 = [[1, 4, 1], [2, 5, 0], [3, 6, 0]]

list3 = [[1, 4, 2], [2, 5, 0], [3, 6, 1]]

希望这能回答你的问题

相关问题 更多 >