![](/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.