7

我有这个当前的列表理解:

...
cur = [[14, k, j] for j, k in rows[14], range(15)]
...

它给了我以下错误:

...        
    cur = [[14, k, j] for j, k in rows[14], range(15)]
ValueError: too many values to unpack

任何帮助,如我将如何解决这个问题。我只是不想手动写出完整的 for 循环或整个列表。谢谢!:D

额外信息:

rows = [{1: '75'},
        {1: '95', 2: '64'}, 
        {1: '17', 2: '47', 3: '82'}, 
        {1: '18', 2: '35', 3: '87', 4: '10'}, 
        {1: '20', 2: '04', 3: '82', 4: '47', 5: '65'}, 
        {1: '19', 2: '01', 3: '23', 4: '75', 5: '03', 6: '34'}, 
        {1: '88', 2: '02', 3: '77', 4: '73', 5: '07', 6: '63', 7: '67'}, 
        {1: '99', 2: '65', 3: '04', 4: '28', 5: '06', 6: '16', 7: '70', 8: '92'}, 
        {1: '41', 2: '41', 3: '26', 4: '56', 5: '83', 6: '40', 7: '80', 8: '70', 9: '33'}, 
        {1: '41', 2: '48', 3: '72', 4: '33', 5: '47', 6: '32', 7: '37', 8: '16', 9: '94', 10: '29'}, 
        {1: '53', 2: '71', 3: '44', 4: '65', 5: '25', 6: '43', 7: '91', 8: '52', 9: '97', 10: '51', 11: '14'}, 
        {1: '70', 2: '11', 3: '33', 4: '28', 5: '77', 6: '73', 7: '17', 8: '78', 9: '39', 10: '68', 11: '17', 12: '57'}, 
        {1: '91', 2: '71', 3: '52', 4: '38', 5: '17', 6: '14', 7: '91', 8: '43', 9: '58', 10: '50', 11: '27', 12: '29', 13: '48'}, 
        {1: '63', 2: '66', 3: '04', 4: '68', 5: '89', 6: '53', 7: '67', 8: '30', 9: '73', 10: '16', 11: '69', 12: '87', 13: '40', 14: '31'}, 
        {1: '04', 2: '62', 3: '98', 4: '27', 5: '23', 6: '09', 7: '70', 8: '98', 9: '73', 10: '93', 11: '38', 12: '53', 13: '60', 14: '04', 15: '23'}]
4

3 回答 3

9

你需要zip他们像这样迭代:

cur = [[14, k, j] for j, k in zip(rows[14], range(15))]
于 2013-05-01T11:50:31.367 回答
5

解释你的代码:

cur = [[14, k, j] for j, k in rows[14], range(15)]

是相同的:

cur = [[14, k, j] for j, k in (rows[14], range(15))]

现在,我们更清楚地看到您已经创建了 atuple并且正在对其进行迭代。第一次通过循环时,元组放弃了rows[14],它是一个包含超过 2 个项目的字典,因此无法将其解包到jandk中。

正如 所指出的jamylak,关键是zip将两个可迭代对象放在一起。

cur = [[14, k, j] for j,k in zip(rows[14],range(15))]

你可以把它想象成一个拉链:

zip(a,b) = [
   (a[0], b[0]),
   (a[1], b[1]),
   (a[2], b[2]),
   ...
   }

以这种方式写出来,你会看到结构有点像拉链(拉链的a左右b部分是和。在你拉上拉链之后,你已经将左边的元素与右边的元素匹配了。当然,您传递给的对象zip不需要是可索引的(重要的是您可以迭代它们),并且您可以将两个以上的可迭代对象“压缩”在一起......

于 2013-05-01T11:56:55.167 回答
2

扩展@jamylak 的答案:或者,您可以使用 map

cur = [[14, k, j] for j, k in map(None,rows[14], range(15))]

这将用 None 填充较短的列表。

于 2013-05-01T11:56:21.500 回答