Python 列表操作错误输出

Python 列表操作错误输出,python,list,python-2.7,for-loop,Python,List,Python 2.7,For Loop,我写了这篇文章: stst = "Hello World!@#" empt = [] def shplit(stst): tst = stst.split() print tst for i in tst: empt = list(i) print empt shplit(stst) 我从指纹中得到的是: ['Hello', 'World!@#'] ['W', 'o', 'r', 'l', 'd', '!', '@', '#'] 我不明

我写了这篇文章:

stst = "Hello World!@#"

empt = []

def shplit(stst):
    tst = stst.split()
    print tst
    for i in tst:
        empt = list(i)
    print empt


shplit(stst)
我从指纹中得到的是:

['Hello', 'World!@#']
['W', 'o', 'r', 'l', 'd', '!', '@', '#']
我不明白为什么“Hello”这个词根本不出现在第二个列表中。
为什么会发生这种情况???

您的缩进不正确:

for i in tst:
    empt = list(i)
print empt # this happens after the loop
当您
print empty
时,循环已经完成,因此您只能看到循环最后一次迭代的值。如果要查看所有迭代,请将
打印缩进一级:

for i in tst:
    empt = list(i)
    print empt # this happens inside the loop

或者,如果您想用所有不同的
i
s填充
empt
,请使用
列表。扩展

for i in tst:
    empt.extend(i)
print empt
这使得:

>>> shplit(stst)
['Hello', 'World!@#']
['H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd', '!', '@', '#']

用你自己的话来说,它为什么会出现?一步一步地看一遍,并解释一下你对
empty
每一步的预期。嗨,你写的最后一块就是我要找的。你能解释一下列表函数和扩展函数之间的区别吗?谢谢\为什么不阅读文档-。您的代码所做的只是每次用一个新列表覆盖
empty