對於一個空的Python列表,往后添加內容有很多種,其中兩種一個是用“+”直接添加內容,另外一種是Listname.append(x)來添加內容
其中,如果處理字符串
在使用“+”的時候,會將字符串拆成一個個列表元素(注:考慮到字符串可以用“[]”操作,所以“當作”列表更貼切),分別添加在列表后面,而用append則是將字符串打包成一個元素,添加到列表中。
例如,如果使用append:
all = []
print "\nEnter lines('.' by itself to quit).\n"
while True:
entry = raw_input(">")
if entry == '.':
all.append(".")
break
else:
all.append(entry)
print all
print "Done!"
假設輸入到內容為hello、world,那么其結果為:
Enter lines('.' by itself to quit).
>hello
>world
>.
['hello', 'world', '.']
Done!
如果是用“+”:
all = []
print "\nEnter lines('.' by itself to quit).\n"
while True:
entry = raw_input(">")
if entry == '.':
all.append(".")
break
else:
all+=(entry)
print all
print "Done!"
那么輸出結果為:
Enter lines('.' by itself to quit).
>hello
>world
>.
['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd', '.']
Done!