Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.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 3.x 使用python reduce()将列表转换为字符串_Python 3.x - Fatal编程技术网

Python 3.x 使用python reduce()将列表转换为字符串

Python 3.x 使用python reduce()将列表转换为字符串,python-3.x,Python 3.x,我正在尝试使用reduce()将输入单词的列表['hdjk','salsap','sherpa']转换为输出:'hdjk salsap sherpa' 以下是我正在尝试处理的代码: from functools import reduce input_list = ['hdjk', 'salsap', 'sherpa'] list(reduce(lambda x,y: x+" "+y, input_list)) # This gives irrelevant output 我也试过: xin

我正在尝试使用reduce()将输入单词的列表['hdjk','salsap','sherpa']转换为输出:'hdjk salsap sherpa'

以下是我正在尝试处理的代码:

from functools import reduce
input_list =  ['hdjk', 'salsap', 'sherpa']
list(reduce(lambda x,y: x+" "+y, input_list)) # This gives irrelevant output
我也试过:

xinpl = [x.split() for x in input_list]
list(reduce(lambda x,y: x+" "+y, xinpl))
这段代码连接了input_列表中的所有元素,它适用于我

print(" ".join(input_list))  
我查看了其他类似的线程,并尝试了很多:


我还是个学习者。大师们,请您帮忙好吗?

代码的
部分工作正常。唯一的问题是它返回一个字符串,然后将其转换为一个列表。只需在
列表(reduce(…)
中删除
列表
,它就会按预期工作

>>> from functools import reduce
>>> input_list =  ['hdjk', 'salsap', 'sherpa']
>>> reduce(lambda x,y: x+" "+y, input_list)
'hdjk salsap sherpa'

你能解释一下为什么你想要reduce而不是
”。加入
?删除
列表中的
列表(reduce(…)
,它就工作了。不管怎样,我找到了答案:@StardustGogeta,谢谢它工作了。:-)@CaldF速度,因为我还是一个学习者,我正在探索和尝试通过不同的方式实现相同的输出。考虑添加一个解释到您的代码,以便它将有助于OP?
input_list = ['All','you','have','to','fear','is','fear','itself']

from functools import reduce

string1 = str(reduce(lambda x,y: x + " " +y, input_list))

print(string1)