在for循环中从列表中解包多个参数

3

我有两个列表。

d1 = ["'02/01/2018'", "'01/01/2018'", "'12/01/2017'"]
d2 = ["'02/28/2018'", "'01/31/2018'", "'12/31/2017'"]

我正在尝试在for循环中对这些值进行解压。
for i,y in d1,d2:
    i,y = Startdate, Enddate

我知道这个迭代会在每个迭代中覆盖StartdateEnddate的值,但现在我只是想成功地解包每个列表中的元素。
我收到以下错误:
too many values to unpack (expected 2)

我以为我正在解包两个变量(d1和d2)


4
for i, y in zip(d1, d2): - Nouman
d1,d2 creates a tuple with two elements, your lists... each of your lists has three elements, which it tries to unpack into i,y - juanpa.arrivillaga
2个回答

4

您需要使用zip。以下是一个使用zip的实例:

>>> a = [1,2,3]
>>> b = [4,5,6]
>>> for i,y in zip(a,b):
    print(i,y)

1 4
2 5
3 6
>>> 

您可以说您的循环可以像这样:
for i,y in zip(d1,d2):
    i,y = Startdate, Enddate

0

在您的示例中,for循环无法“解包”多个列表,但是您可以像@Nouman提到的那样进行'zip'

list(zip([1, 2, 3], ['a', 'b', 'c'])) --> [(1, 'a'), (2, 'b'), (3, 'c')]

现在,您可以每次解压两个日期...


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接