Python 用于列表元素串联的函数?
我想创建一个函数,将列表中的所有字符串连接起来并返回结果字符串。我试过这样的东西Python 用于列表元素串联的函数?,python,list,function,python-3.x,Python,List,Function,Python 3.x,我想创建一个函数,将列表中的所有字符串连接起来并返回结果字符串。我试过这样的东西 def join_strings(x): for i in x: word = x[x.index(i)] + x[x.index(i) + 1] return word #set any list with strings and name it n. print join_strings(n) 但它不起作用,我也不知道为什么。这个问题有什么解决办法,或者我的想法有什么改变?我先
def join_strings(x):
for i in x:
word = x[x.index(i)] + x[x.index(i) + 1]
return word
#set any list with strings and name it n.
print join_strings(n)
但它不起作用,我也不知道为什么。这个问题有什么解决办法,或者我的想法有什么改变?我先谢谢你 对于实际工作,请使用'.join(x)
代码的问题在于每次迭代都在更改word
,而不保留以前的字符串。
尝试:
这是使用累加器的一般模式的示例。保存信息并在不同循环/递归调用中更新的东西。这种方法几乎可以按原样工作(除了word=''
部分),用于连接列表和元组等,或者对任何内容求和-实际上,它接近于重新实现sum
内置函数。一个更接近的例子是:
def sum(iterable, s=0):
acc = s
for t in iterable:
acc += s
return acc
当然,对于字符串,您可以使用'.join(x)
实现相同的效果,通常(数字、列表等)可以使用sum
函数。更一般的情况是用一般操作替换+=
:
from operator import add
def reduce(iterable, s=0, op=add):
acc = s
for t in iterable:
acc = op(w, s)
return acc
@IonutHulub这取决于您是否想要连接字符串,或者您是否想要学习如何连接字符串。OP问他的代码中有什么问题。@IonutHulub这回答了这个问题,但是建议
''还是不错的。最后加入completeness@IonutHulub阅读我最后一条评论的这一部分:“很高兴建议”。为了完整起见,请在结尾处加入”@user2460125:use-join,既然你知道自己该怎么做了。@jamylak,建议一下可不太好。这是唯一正确的做法。在python中连接字符串的任何其他方法都是愚蠢的。您知道内置的join
方法比使用+
运算符连接字符串快多少吗?更不用说编写代码要快得多。
from operator import add
def reduce(iterable, s=0, op=add):
acc = s
for t in iterable:
acc = op(w, s)
return acc