0

I want to create a function which concatenates all the strings within a list and returns the resulting string. I tried something like this

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)

but it doesn't work and I can't figure out why. Any solution to the problem or fix of my thought? I thank you in advance!

4

1 回答 1

1

对于实际工作,请使用''.join(x).

您的代码的问题是您正在更改word每次迭代,而没有保留以前的字符串。尝试:

def join_strings(x):
    word = ''
    for i in x:
        word += i
    return 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
于 2013-06-07T09:57:28.393 回答