简体   繁体   English

使用列表推导解包嵌套元组

[英]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)结果是: 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?你有没有注意到带有Start的元素实际上是三个元素? 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:] .使用path[3:]而不是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.您收到“太多值”错误的原因是它试图解压缩'Start' ,它是 5 长,而不是 3 长。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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