遍歷列表的全部元素,對每一個元素執行相同的操做。可以使用for循環app
magicians = ['alice','david','carolina'] for magician in magicians:
print(magician)
運行結果
alice
david
carolina
magicians = ['alice','david','carolina'] for magician in magicians: #print(magician) print(magician.title() + ", that was a great trick!") print("I can't wait to see your next trick, " + magician.title() + ".\n") print("Thank you, everyone. That was a great magic show!")
運行結果
Alice, that was a great trick! I can't wait to see your next trick, Alice. David, that was a great trick! I can't wait to see your next trick, David. Carolina, that was a great trick! I can't wait to see your next trick, Carolina. Thank you, everyone. That was a great magic show!
一,列表很是適合用於存儲數字集合,函數range()可以輕鬆生成一系列的數字。 ide
for value in range(1,5): print(value)
運行結果
1
2
3
4
二,使用range()建立數字列表。可以使用函數list()將range()的結果直接轉換成列表。還可指定步長。函數
numbers = list(range(1,6)) print(numbers)
運行結果
[1, 2, 3, 4, 5]
3、列表解析spa
列表解析將for循環和建立新元素的代碼合併成一行,並自動附加新元素。code
語法:描述性的列表名 = 【表達式(用於存儲到列表中的值) for循環】blog
squares = [] for value in range(1,11): squares.append(value**2) print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
squares = [value**2 for value in range(1,11)] print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
4、切片three
1,處理列表的部分元素-稱之爲切片 ci
players = ['charles','martina','michael','florence','eli'] print(players[0:3]) print(players[1:4]) print(players[:4]) print(players[2:]) print(players[-3:]) print(players[:-3])
['charles', 'martina', 'michael'] ['martina', 'michael', 'florence'] ['charles', 'martina', 'michael', 'florence'] ['michael', 'florence', 'eli'] ['michael', 'florence', 'eli'] ['charles', 'martina']
2,遍歷切片it
players = ['charles','martina','michael','florence','eli'] print("\nHere are the first three players on my team:") for player in players[:3]: print(player.title())
運行結果:
Here are the first three players on my team:
Charles
Martina
Michael
3,複製列表io
Python的元組與列表相似,不一樣之處在於元組的元素不能修改。
元組使用小括號,列表使用方括號。
元組建立很簡單,只須要在括號中添加元素,並使用逗號隔開便可。
以下實例:
dimensions = (200,50) #dimensions[0] = 250 修改無組值報錯 print(dimensions[0]) print(dimensions[1]) #遍歷元組中的全部值,for循環 for dimension in dimensions: print(dimension) @修改元組變量 dimensions = (250,50) print("\nModified dimensions:") for dimension in dimensions: print(dimension)
運行結果: 200 50 200 50 Modified dimensions: 250 50