脚本内容
ten_things = "Apple Orange Crow Telephone Light Sugar"
print("Wait there's not 10 things in that lists,let's fix it.")
stuff = ten_things.split(' ') #根据空格将ten_things分割开来
more_stuff = ["Day","Night","Song","Rice","Corn","Banana","Girl","Boy"]
while len(stuff) != 10: #一直循环执行,直到stuff元素个数>=10
next_one = more_stuff.pop() #pop默认是从最后一个开始,也即将more_stuff列表里的最后一个元素返回到next_one中
print("Adding:",next_one)
stuff.append(next_one)
print("There is %d items now." %len(stuff)) #报告当前stuff的元素个数
print("Now we have:",stuff) #将当前的10个元素列出来
print("Let's do something with stuff.")
print(stuff[1]) #第二个元素
print(stuff[-1]) #倒数第一个元素
print(stuff.pop()) #pop默认是最后一个元素,同上
print(' '.join(stuff)) #用空格将stuff的各个元素连接起来
print('#'.join(stuff[3:5])) #用#号将stuff的第四个(3)元素和第五个(5)元素连接起来,包头不包尾
运行结果
PS E:\tonyc\Documents\Vs workspace> cd 'e:\tonyc\Documents\Vs workspace'; ${env:PYTHONIOENCODING}='UTF-8'; ${env:PYTHONUNBUFFERED}='1'; & 'D:\Anboot\Python\python.exe' 'c:\Users\tonyc\.vscode\extensions\ms-python.python-2019.3.6558\pythonFiles\ptvsd_launcher.py' '--default' '--client' '--host' 'localhost' '--port' '59613' 'e:\tonyc\Documents\Vs workspace\The Hard Way\ex39(列表).py'
Wait there's not 10 things in that lists,let's fix it.
Adding: Boy
There is 7 items now.
Adding: Girl
There is 8 items now.
Adding: Banana
There is 9 items now.
Adding: Corn
There is 10 items now.
Now we have: ['Apple', 'Orange', 'Crow', 'Telephone', 'Light', 'Sugar', 'Boy', 'Girl', 'Banana', 'Corn']
#10个元素,首先是stuff被split用空格分开,添加到10个之后,打印出来,是一个列表
Let's do something with stuff.
Orange
Corn
Corn
Apple Orange Crow Telephone Light Sugar Boy Girl Banana #因为上面使用了pop,所以最后一个元素Corn已经被去除
Telephone#Light