简体   繁体   中英

Unpacking nested tuples using list comprehension

I have a list:

path = [
    (5, 5),
    'Start',
    0,
    ((5, 4), 'South', 1),
    ((5, 3), 'South', 1),
    ((4, 3), 'West', 1),
    ((4, 2), 'South', 1),
    ((3, 2), 'West', 1),
    ((2, 2), 'West', 1),
    ((2, 1), 'South', 1),
    ((1, 1), 'West', 1)]

I am trying to extract all the directions (except for the first one that says 'Start') so that I have a new list:

directions = ['South', 'South', 'West', 'South', 'West', 'West', 'South', 'West']

I have tried the following:

for (x, y), direction, cost in path[1:]:  # [1:] to omit the first direction
     directions.append(direction)

The result is: ValueError: too many values to unpack (expected 3)

I have also tried unpacking by using the following:

result = [(x, y, direction, cost) for (x, y), direction,cost in path[1:]]

It gives the same error. The tuple within a tuple within a list is really confusing me. Thanks in advance for any insight, I greatly appreciate it!

Did you notice that the element with Start is actually three elements? When encapsulating the first three elements in a tuple, you'll get it right:

path = [
    ((5, 5), 'Start', 0),
    ((5, 4), 'South', 1),
    ((5, 3), 'South', 1),
    ((4, 3), 'West', 1),
    ((4, 2), 'South', 1),
    ((3, 2), 'West', 1),
    ((2, 2), 'West', 1),
    ((2, 1), 'South', 1),
    ((1, 1), 'West', 1)]

result = [(x, y, direction, cost) for (x, y), direction, cost in path[1:]]
print(result)

out:

[(5, 4, 'South', 1), (5, 3, 'South', 1), (4, 3, 'West', 1), (4, 2, 'South', 1), (3, 2, 'West', 1), (2, 2, 'West', 1), (2, 1, 'South', 1), (1, 1, 'West', 1)]

I just reformatted the code in the question for readability and accidentally made the problem a lot more obvious: The first three elements of the list aren't in a tuple. Use path[3:] instead of path[1:] .

The reason you're getting that error "too many values" is that it's trying to unpack 'Start' , which is 5 long, not 3.

>>> [direction for (_x, _y), direction, _cost in path[3:]]
['South', 'South', 'West', 'South', 'West', 'West', 'South', 'West']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM