1. for循環(huán)
for magician in magicians: ?#這里注意for循環(huán)后面有一個(gè)冒號(hào)
? ? ?print(magician) #以及print這一行前面必須有空格洋腮,類似\t
打印出來的結(jié)果分為多行
pizzas = ['pepper','chicken','fruit']
for pizza in pizzas:
? ? ?print("I like " + pizza + "pizza!")
print("I really like pizzas!") ?#在循環(huán)結(jié)束后的末尾輸出一行
pizzas = ['pepper','chicken','fruit']
for pizza in pizzas:
? ? ? print("I like " + pizza + "pizza!")
? ? ? print("I really like pizzas!") ?#在每一行輸出都加上一行
pizzas = ['pepper','chicken','fruit']
for pizza in pizzas:
? ? ? ?print("I like " + pizza + "pizza!")
print("I really like " + pizza + " pizza!") ?#這里會(huì)輸出最后一個(gè)pizza的名字但是不會(huì)報(bào)錯(cuò)
2. 創(chuàng)建數(shù)值列表
使用函數(shù)range():
for value in range(1,6):
? ? ? print(value) #打印1-5這5個(gè)數(shù)字像鸡,從第一個(gè)數(shù)開始數(shù)域慷,但是不包括第二個(gè)數(shù)
輸出列表:
even_numbers = list(range(2,11,2)) ?#這里range從2開始,加2遞增区匣,到小于11結(jié)束
print(even_numbers) ?#輸出[2,4,6,8,10] #list的作用是將上述結(jié)果轉(zhuǎn)換為列表
squares = []
for value in range(1,11):
? ? ? squares.append(value ** 2) ?#輸出從1~10的平方
print(squares)
3. 切片
players = ['charles','martina','michael','florence','eli']
print(players[0:3]) ?#截取從0開始,到索引3結(jié)束(不包括索引3)
print(players[1:4]) #從索引1開始,到索引4結(jié)束(不包括索引4)
print(players[:4]) #從索引0開始陨帆,到索引4結(jié)束(不包括索引4)
print(players[2:]) #從索引2開始骚亿,到最后一個(gè)元素
print(players[-3:])
for player in players[:3]: #遍歷前三個(gè)列表
? ? ? print(player.title())
my_foods = ['pizza','falafel','carrot']
friend_foods = my_foods[:] #復(fù)制my_foods到friend_foods列表中
print(friend_foods) #不能使用friend_foods = my_foods直接進(jìn)行復(fù)制
4. 元組
元組中的值是不能被修改的已亥。
dimensions = (200,50,70,30,'test')
print(dimensions[0])
print(dimensions[1])
print(dimensions[-1]) ?#其他定義類似列表的定義
dimensions[0] = 40? #不能賦值 會(huì)報(bào)錯(cuò) TypeError: 'tuple' object does not support item assignment
print(dimensions[0])
for dimension in dimensions:
print(dimension) ?#元組的遍歷
dimensions = ('a','b','c')
print(dimensions) ?#dimensions中的元素不可以單獨(dú)賦值,但是可以整個(gè)修改dimensions