如何追加字符串 - Python

Mat*_*ker -2 python python-2.7

我正在尝试编写一个接受数组的函数,将其转换为字符串,然后将其附加在一起.

防爆.[1,2,3,4,5,6]会回来的'123456'.

这是我已经尝试过的代码,但它给出了错误"list indices必须是整数,而不是str"

a = [1,2,3,4,5,6,7,8,9,10]

def add_it_up(a,b):
    return a+b

def to_str(a):
    for i in a:
        a[i] = str(a[i])

    reduce(add_it_up, a)
Run Code Online (Sandbox Code Playgroud)
a = [1,2,3,4,5,6,7,8,9,10]

def to_str(a):

    ''.join(map(str, l))
    return a
Run Code Online (Sandbox Code Playgroud)

上面的代码有什么问题?它只是返回原始值.

ars*_*jii 10

不要重新发明轮子:

>>> l = [1,2,3,4,5,6]
>>> 
>>> ''.join(map(str, l))
'123456'
Run Code Online (Sandbox Code Playgroud)

你的代码中的问题是forPython中的循环实际上是for-each循环.所以,当你碰到这样的for i in a,i需要对所有的元素a,而不是指数a.

因此,您的循环实际上可以在一次迭代中正常工作,并且您已成功将列表元素设置为字符串(特别是索引处的元素1,因为这是第一个值i).但是,下一个i将引用此新的字符串元素,因此会导致错误a[i].

这是一个有趣的现象,所以让我们看一下简化列表a = [1,2,3],它是你的子列表,a足以看出错误的发生位置和原因:

+-----+-----+-----+
|  1  |  2  |  3  |
+-----+-----+-----+
   ^
   i (loop starts, i takes on first value of list: 1)

+-----+-----+-----+
|  1  | '2' |  3  |
+-----+-----+-----+
   ^
   i (we set element at index i (a[1]) to str(a[1]), which is '2')

+-----+-----+-----+
|  1  | '2' |  3  |
+-----+-----+-----+
         ^ 
         i (next iteration, i takes on second value: '2')

Error occurs with a[i], list indices must be integers.

参考