![](/img/trans.png)
[英]I am getting the error test_verified_email - TypeError: 'NoneType' object is not callable.This error happens the 1st time I run the code. Why is this?
[英]I am getting 'list' object is not callable error for this code. I need to add zero before each element
a = [1,2,3,4]
newarray = list(map(a,[0,*a]))
print(newarray)
output:
'list' object 不是可调用错误
预期:将零添加到数组中的每个元素
只需使用列表理解:
out = [[0,x] for x in a]
output: [[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)
output: [(0, 1), (0, 2), (0, 3), (0, 4)]
由于您的评论不完全清楚(“在字符串 0 前面加上”),如果您真的想要strings ,您可以使用:
out = [f'0{x}' for x in a]
或者
out = list(map('{:02d}'.format, a))
output: ['01', '02', '03', '04']
内置 function map
需要两个 arguments:一个 function 和一个列表。
您以错误的顺序编写了 arguments:您首先传递a
列表而不是第二个。
而你试图作为 function 传递的东西并不是真正的 function。
这是通过使用def
定义 function 来解决的可能方法:
def the_function_for_map(x):
return [0, x]
newarray = list(map(the_function_for_map, a))
这是通过使用lambda
定义 function 来解决的可能方法:
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.