Python之Tuple遍歷方式
阿新 • • 發佈:2019-01-05
Tuple的同樣需要遍歷嘛,只是一旦建立後,元素不可變,遍歷同List一樣
分開寫的原因是,就像那位大牛說的,層級都不要太深,本來就low,一下子放在一起,知識不好鞏固
0、直接上乾貨,第一種:for in
girl_tuple = ("貂蟬", "狐狸精","範金鏈","翠花","小班")
for everyOne in girl_tuple:
print(everyOne)
輸出結果:
貂蟬
狐狸精
範金鏈
翠花
小班
1、第二種,使用內建函式enumerate,但我怎麼也找到一個同名的class
girl_tuple = ("貂蟬", "狐狸精","範金鏈","翠花","小班") for index, everyOne in enumerate(girl_tuple): print str(index) + everyOne
輸出結果:
0貂蟬
1狐狸精
2範金鏈
3翠花
4小班
2、第三種,使用range()或者xrange(),這倆內建函式,會把傳入的數字,分解成一個List,比如range(5),那就是[0,1,2,3,4]
girl_tuple = ("貂蟬", "狐狸精","範金鏈","翠花","小班")
for index in range(len(girl_tuple)):
print girl_tuple[index]
girl_tuple = ("貂蟬", "狐狸精","範金鏈","翠花","小班") for index in xrange(len(girl_tuple)): print girl_tuple[index]
輸出結果:
貂蟬
狐狸精
範金鏈
翠花
小班
3、第四種,使用iter(),同樣是內建函式,返回迭代器,牛x
girl_tuple = ("貂蟬", "狐狸精","範金鏈","翠花","小班")
for everyOne in iter(girl_tuple):
print everyOne
輸出結果:
貂蟬
狐狸精
範金鏈
翠花
小班