开发者

Problem unpacking list of lists in a for loop?

开发者 https://www.devze.com 2023-01-05 14:16 出处:网络
I have a list of lists that I want to unpack in for loops, but I\'m running into an issue. >>> a_list = [(date(2010, 7, 5), [\'item 1\', \'item 2\']), (date(2010, 7, 6), [\'item 1\'])]

I have a list of lists that I want to unpack in for loops, but I'm running into an issue.

>>> a_list = [(date(2010, 7, 5), ['item 1', 'item 2']), (date(2010, 7, 6), ['item 1'])]
>>>
>>> for set in a_list:
...     a, b = set
...     print a, b
...
2010-07-05 ['item 1', 'item 2']
2010-07-06 ['item 1']
>>>
>>> for set in a_list:
...     for a, b in set:
...             print a, b
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module&开发者_Python百科gt;
TypeError: 'datetime.date' object is not iterable

How come the first one works, but the second one doesn't?


I think you're looking for something like this:

>>> for a, b in a_list:
    print(a, b)


2010-07-05 ['item 1', 'item 2']
2010-07-06 ['item 1']

Also, note, set is a bad name for a variable as it shadows built-in.


Mostly because they are completely different:

In the first loop, set is (date(2010, 7, 5), ['item 1', 'item 2']) and you unpack it. a,b and set have the same length so this works.

In the 2nd you loop over set (a tuple with 2 elements, that's why you can loop over it) and try to unpack the first element: The first iteration of the loop does tmp = set[0] which is date(2010, 7, 5), then you try a,b = tmp which fails with the given error message.


for a,b in set is equivalent to a,b = set[0] ... loop ... a,b = set[1] ... loop ...

So Python tried to unpack the first element in set into the tuple a,b which doesn't work.

0

精彩评论

暂无评论...
验证码 换一张
取 消