我收到“列表”;此代码的对象不可调用错误。我需要在每个元素之前添加零

发布于 2025-01-15 23:39:02 字数 170 浏览 5 评论 0原文

a = [1,2,3,4]

newarray = list(map(a,[0,*a]))

print(newarray)

输出:

“列表”对象不可调用错误

预期错误:向数组中的每个元素添加零

a = [1,2,3,4]

newarray = list(map(a,[0,*a]))

print(newarray)

output:

'list' object is not callable error

expected: Add zero to each element in array

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

无需解释 2025-01-22 23:39:02

只需使用列表理解:

out = [[0,x] for x in a]

输出:[[0, 1], [0, 2], [0, 3], [0, 4]]

或者,itertools.repeatzip:

from itertools import repeat
out = list(zip(repeat(0), a))
# or keep a generator
# g = zip(repeat(0), a)

输出:[(0, 1), (0, 2), (0, 3), (0, 4)]

字符串

,因为您的评论不完整明确(“前缀字符串0”),如果您确实想要字符串,您可以使用:

out = [f'0{x}' for x in a]

out = list(map('{:02d}'.format, a))

输出:['01', '02', '03', '04']

Just use a list comprehension:

out = [[0,x] for x in a]

output: [[0, 1], [0, 2], [0, 3], [0, 4]]

Alternatively, itertools.repeat and zip:

from itertools import repeat
out = list(zip(repeat(0), a))
# or keep a generator
# g = zip(repeat(0), a)

output: [(0, 1), (0, 2), (0, 3), (0, 4)]

strings

as your comment is not fully clear ("prepending the string 0"), in case you really want strings, you can use:

out = [f'0{x}' for x in a]

or

out = list(map('{:02d}'.format, a))

output: ['01', '02', '03', '04']

滥情稳全场 2025-01-22 23:39:02

内置函数 map 需要两个参数:一个函数和一个列表。

您以错误的顺序编写了参数:您首先传递了列表 a 而不是第二个。

而你试图作为函数传递的东西并不是真正的函数。

这是通过使用 def 定义函数的可能修复:

def the_function_for_map(x):
    return [0, x]

newarray = list(map(the_function_for_map, a))

这是通过使用 lambda 定义函数的可能修复:

newarray = list(map(lambda x: [0, x], a))

最后,这是使用列表理解的可能修复而不是 map

newarray = [[0, x] for x in a]

在您的特定情况下,您还可以将 zip 与全零列表一起使用:

newarray = list(zip([0]*len(a), a))

或将 zip_longest 与空列表和默认值:

from itertools import zip_longest

newarray = list(zip_longest([], a, fillvalue=0))

Builtin function map expects two arguments: a function and a list.

You wrote your arguments in the wrong order: you passed list a first instead of second.

And the thing you tried to pass as a function is not really a function.

Here is a possible fix by defining a function with def:

def the_function_for_map(x):
    return [0, x]

newarray = list(map(the_function_for_map, a))

Here is a possible fix by defining a function with lambda:

newarray = list(map(lambda x: [0, x], a))

And finally, here is a possible fix using a list comprehension instead of map:

newarray = [[0, x] for x in a]

In your particular case, you can also use zip with a list full of zeroes:

newarray = list(zip([0]*len(a), a))

Or zip_longest with an empty list and a default value:

from itertools import zip_longest

newarray = list(zip_longest([], a, fillvalue=0))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文