笨辦法38列表操作
阿新 • • 發佈:2018-01-06
ber pop 方便 cor some org div 分割 www
- split(python基礎教程p52)
非常重要的字符串方法,是join的逆方法,用來將字符串分割成序列;
- len(python基礎教程p33)
內建函數len,返回序列中包含元素的數量;
- pop(python基礎教程p38)
pop方法,移除列表中的最後(默認)一個元素,並返回該元素的值,用法如下:
>>> x = [1, 2, 3] >>> x.pop() 3 >>> x [1, 2] >>> x.pop(0) 1 >>> x [2]
- append(python基礎教程p36)
append方法用於在列表末尾追加新對象;
- 分片(python基礎教程p29)
訪問一定範圍內的元素,前一個索引的元素包含在分片內,後一個不包含在分片內
>>> numbers = [1, 2, 3, 4, 5, 6] >>> numbers[2,5] [3, 4, 5] >>> numbers[0, 1] [1]
>>> tag = ‘<a href="http://www.python.org">Python web site</a>‘
>>> tag[9:30]
‘http://www.python.org‘
>>> tag[32:-4]
‘Python web site‘
(從“<”開始計數,即“<”是第0個元素)
以下為代碼,加了一些print("test",xxxxxxxx)方便檢查
1 ten_things = "Apples Oranges Crows Telephone Light Sugar" 2 3 print("Wait there are not 10 things in that list. Let‘s fix that.") 4 5 stuff = ten_things.split(‘ ‘) 6 # print("test", stuff) 7 8 more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"] 9 10 while len(stuff) != 10: 11 next_one = more_stuff.pop() 12 # print("test", more_stuff) 13 print("Adding:", next_one) 14 stuff.append(next_one) 15 # print("test",stuff) 16 print("There are %d items now." % len(stuff)) 17 18 print("There we go:", stuff) 19 20 print("Let‘s do some things with stuff.") 21 22 print(stuff[1]) 23 print(stuff[-1]) # whoa! fancy 24 print(stuff.pop()) 25 # print("test", stuff) 26 print(‘ ‘.join(stuff)) # what? cool! 27 # print("test", stuff[3:5]) 28 print(‘#‘.join(stuff[3:5])) #super stellar!
笨辦法38列表操作