使用列表理解解包嵌套元组
Unpacking nested tuples using list comprehension
我有一个列表:
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)]
我正在尝试提取所有方向(除了第一个说 'Start' 的方向)以便我有一个新列表:
directions = ['South', 'South', 'West', 'South', 'West', 'West', 'South', 'West']
我尝试了以下方法:
for (x, y), direction, cost in path[1:]: # [1:] to omit the first direction
directions.append(direction)
结果是:ValueError: too many values to unpack (expected 3)
我也试过使用以下方法解包:
result = [(x, y, direction, cost) for (x, y), direction,cost in path[1:]]
它给出了同样的错误。列表中的元组中的元组真的让我感到困惑。在此先感谢您的任何见解,我非常感谢!
有没有发现,Start
的元素实际上是三元素?
将前三个元素封装在一个元组中时,你会得到它:
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)
输出:
[(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)]
我只是为了可读性重新格式化了问题中的代码,不小心使问题变得更加明显:列表的前三个元素不在元组中。使用 path[3:]
而不是 path[1:]
.
您收到“太多值”错误的原因是它正在尝试解压缩 'Start'
,它的长度为 5,而不是 3。
>>> [direction for (_x, _y), direction, _cost in path[3:]]
['South', 'South', 'West', 'South', 'West', 'West', 'South', 'West']
我有一个列表:
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)]
我正在尝试提取所有方向(除了第一个说 'Start' 的方向)以便我有一个新列表:
directions = ['South', 'South', 'West', 'South', 'West', 'West', 'South', 'West']
我尝试了以下方法:
for (x, y), direction, cost in path[1:]: # [1:] to omit the first direction
directions.append(direction)
结果是:ValueError: too many values to unpack (expected 3)
我也试过使用以下方法解包:
result = [(x, y, direction, cost) for (x, y), direction,cost in path[1:]]
它给出了同样的错误。列表中的元组中的元组真的让我感到困惑。在此先感谢您的任何见解,我非常感谢!
有没有发现,Start
的元素实际上是三元素?
将前三个元素封装在一个元组中时,你会得到它:
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)
输出:
[(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)]
我只是为了可读性重新格式化了问题中的代码,不小心使问题变得更加明显:列表的前三个元素不在元组中。使用 path[3:]
而不是 path[1:]
.
您收到“太多值”错误的原因是它正在尝试解压缩 'Start'
,它的长度为 5,而不是 3。
>>> [direction for (_x, _y), direction, _cost in path[3:]]
['South', 'South', 'West', 'South', 'West', 'West', 'South', 'West']