Python - 在for中列出具有多个参数的理解

时间:2013-05-01 11:49:35

标签: python list list-comprehension

我有这个当前列表理解:

...
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'}]

3 个答案:

答案 0 :(得分:9)

你需要zip他们这样迭代:

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

答案 1 :(得分: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))]

现在,我们更清楚地看到您已创建了tuple并正在迭代它。第一次循环时,元组放弃rows[14],这是一个包含2个以上项目的字典,因此无法将其解压缩到jk。< / p>

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]),
   ...
   }
用这种方式写出来,你会看到结构类似于拉链(ab是拉链的左右两部分。拉链之后,你已经匹配了一个拉链。左边的元素和右边的元素。当然,传递给zip的对象不需要是可索引的(重要的是你可以迭代它们),你可以“压缩”超过2次迭代...

答案 2 :(得分:2)

扩展@ jamylak的答案:或者你可以使用地图

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

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