【发布时间】:2020-08-19 07:07:08
【问题描述】:
我正在尝试对来自不同列表的多个项目并行执行一个公式。
- 首先我的清单如下:
l1= [1,2,3]
l2= [4,5,6]
l3= [7,8,9]
- 接下来我需要从我的主列表中创建一组新列表,以便比较列表中的每对元素:
newl1 = list(zip(l1, l1[1:])) #outputs [(1,2), (2,3)]
newl2 = list(zip(l2, l2[1:])) #outputs [(4,5), (5,6)]
newl3 = list(zip(l3, l3[1:])) #outputs [(7,8), (8,9)]
- 现在我想并行遍历所有新列表集,并能够比较元组列表元素:
for pair_of_newl1, pair_of_newl2, pair_of_newl3 in newl1, newl2, newl3:
if pair_of_newl1[0] > pair_of_newl1[1]:
x = pair_of_newl1[0] + pair_of_newl2[1] + pair_of_newl3[1]
print (x)
elif pair_of_newl1[0] < pair_of_newl1[1]:
x = pair_of_newl1[0] - pair_of_newl2[1] - pair_of_newl3[1]
print (x)
预计在第一次迭代中:
pair_of_newl1 = (1,2)
pair_of_newl2 = (4,5)
pair_of_newl3 = (7,8)
因此能够通过索引来比较其中的项目。
我收到以下错误:
ValueError: not enough values to unpack (expected 3, got 2)
我很困惑,删除了最后一个列表,只剩下两个列表可以使用:
l1= [1,2,3]
l2= [4,5,6]
newl1 = list(zip(l1, l1[1:])) #outputs [(1,2), (2,3)]
newl2 = list(zip(l2, l2[1:])) #outputs [(4,5), (5,6)]
for pair_of_newl1, pair_of_newl2 in newl1, newl2:
if pair_of_newl1[0] > pair_of_newl1[1]:
x = pair_of_newl1[0] + pair_of_newl2[1]
print (x)
elif pair_of_newl1[0] < pair_of_newl1[1]:
x = pair_of_newl1[0] - pair_of_newl2[1]
print (x)
print (pair_of_newl1, pair_of_newl2) #just to see how the loop works
我得到了:
-1
(1, 2) (2, 3)
-1
(4, 5) (5, 6)
所以根据我的理解,pair_of_newl2 被视为 newl1 的第二项,但为什么不是 newl2 呢?
请帮忙。
【问题讨论】:
-
考虑到在这种情况下只满足第二个条件,我希望 x = 1 - 5
标签: python python-3.x iteration