Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何编写包含for循环的Lambda_Python_Python 2.7_For Loop_Lambda - Fatal编程技术网

Python 如何编写包含for循环的Lambda

Python 如何编写包含for循环的Lambda,python,python-2.7,for-loop,lambda,Python,Python 2.7,For Loop,Lambda,我试图使空列表的长度与字符串中的字母数相同: string = "string" list = [] #insert lambda here that produces the following: # ==> list = [None, None, None, None, None, None] lambda应执行与此代码等效的操作: for i in range(len(string)): list.append(None) 我尝试了以下lambda: lambda x:

我试图使空列表的长度与字符串中的字母数相同:

string = "string"
list = []
#insert lambda here that produces the following:
# ==> list = [None, None, None, None, None, None]
lambda应执行与此代码等效的操作:

for i in range(len(string)):
     list.append(None)
我尝试了以下lambda:

lambda x: for i in range(len(string)): list.append(None)
但是,它不断回复
语法错误
,并突出显示
的单词


我的lambda怎么了?你不需要lambda来做这个。您所需要的只是:

[None] * len(string)
为什么不倍增

>>> lst = [None]*5
>>> lst
[None, None, None, None, None]
>>> lst[1] = 4
>>> lst
[None, 4, None, None, None]
为什么不列出理解

>>> lst = [None for x in range(5)]
>>> lst
[None, None, None, None, None]
>>> lst[3] = 9
>>> lst
[None, None, None, 9, None]
但是……对于兰姆达:

>>> k=lambda x: [None]*x
>>> lst = k(5)
>>> lst
[None, None, None, None, None]
>>> lst[4]=8
>>> lst
[None, None, None, None, 8]

您需要一个lambda,它接受一个字符串
s
,并返回一个长度
len(s)
的列表,其所有元素都是
None
。不能在lambda中使用
for
循环,因为
for
循环是语句,但lambda的主体必须是表达式。但是,该表达式可以是列表理解,您可以在其中进行迭代。以下内容将实现此目的:

to_nonelist = lambda s: [None for _ in s]

>>> to_nonelist('string')
[None, None, None, None, None, None]

lambda只能包含表达式,而
for
是一条语句。