【问题标题】:Iterating over a nested list and copying the values using list comprehensions迭代嵌套列表并使用列表推导复制值
【发布时间】:2014-08-29 11:11:15
【问题描述】:

我在尝试迭代 python 中的嵌套列表时遇到问题,并将列表中的值复制到另一个嵌套列表中,同时为每个值添加一个。

假设我有一个清单

input = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

我尝试创建第二个列表(称为output)是:

output = [[x + 1 for int(x)in y] for y in input]

这给了我错误

SyntaxError: can't assign to function call

编辑:

感谢答案,问题是试图调用 int(x) - 这完全没有必要。此外,我调用列表input

似乎没有问题

【问题讨论】:

  • 我想你只是在:[[x + 1 for x in y] for y in input] - 不知道你想用你的int 电话做什么 - 他们已经是ints...
  • 包含完整的错误回溯通常会有所帮助,而不是“根本不起作用”

标签: python list nested list-comprehension


【解决方案1】:

你有几个问题:

  1. inputbuilt-in function,所以你不应该把它用作变量名;
  2. 在您的内部列表理解中in 之前缺少一个空格;和
  3. 您正尝试将 y 中的每个值依次分配给 int(x),因此出现错误消息 can't assign to function call

int 调用无论如何都是不必要的,因为您的值已经是整数。

请尝试:

input_ = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
output = [[x + 1 for x in y] for y in input_]

【讨论】:

    【解决方案2】:

    int(x)移到左侧

    output = [[int(x) + 1 for x in y] for y in input]
    

    实际上,由于y 已经是int 类型,你不必再次调用int(x)[x + 1 for x in y] 可以正常工作

    【讨论】:

    • 也不要使用输入作为变量名
    猜你喜欢
    • 1970-01-01
    • 2017-02-17
    • 2012-08-09
    • 2011-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-27
    相关资源
    最近更新 更多