a = [1,2,3,4]
newarray = list(map(a,[0,*a]))
print(newarray)
输出:
'list'对象不可调用错误
预期:将零添加到数组中的每个元素
只需使用列表理解:
out = [[0,x] for x in a]
输出:[[0, 1], [0, 2], [0, 3], [0, 4]]
或者,itertools.repeat
和zip
:
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']
内置函数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))