用for迴圈遍歷(字串,列表,元組,集合,字典)

2021-09-28 13:51:49 字數 1746 閱讀 7526

#字串

>>> str = 'abcd'

>>> for value in str :

... print(value)ab

cd>>> #列表

>>> lst = ['a','b','c']

>>> for value in lst :

... print(value)ab

c>>> # 將列表元素遍歷出來,還有索引

>>> lst = ['a','b','c']

>>> for value in enumerate(lst):

... print(value)

...(0, 'a')

(1, 'b')

(2, 'c')

>>> for value in enumerate(lst):

... print(value[0],value[1])

...0 a

1 b2 c

>>> #元組

...>>> for value in enumerate((1,5)):

... print(value)

...(0, 1)

(1, 5)

>>> for value in enumerate((1,5)):

... print(value[0],value[1])

...0 1

1 5

遍歷字典

>>> my_dict = 

>>> for key in my_dict: # 預設遍歷key

... print(key)

...name

age>>> for key in my_dict.keys(): # 方法keys()與預設遍歷一致

... print(key)

...name

age>>> users =

>>> if 'sarah' in users.keys():

... print('hello')

...hello

>>> users =

>>> for key in sorted(users.keys()):

... print(key)

...henle

sarah

tom>>> for value in my_dict.values(): # 遍歷value

... print(value)

...張三

18>>> for value in set(users.values()): #使用set函式踢出遍歷中的重複值

... print(value)

...python

ruby

>>> for key,value in my_dict.items(): # 遍歷key和value

... print(key,value)

...name 張三

age 18

集合

>>> my_set = 

>>> for value in my_set:

... print(value)

...1

23

字串 列表 元組

字串常用方法 s my name is jike.i am 18 print s.upper 全部轉成大寫 print s.lower 全部轉成小寫 print s.title 將字串中單詞首字母大寫 print s.strip 去除兩邊的空格 print s.count m 統計字元出現的次數 p...

字串,列表,元組

1,字串 str1 hello world print len str1 計算字串的長度 print str1.capitalize 首字母大寫 print str1.upper 所有字母大寫 print str1.lower 所有字母小寫 print str1.find ll 從字串中查詢子串的位...

字串,列表,元組

字串,列表,元組,練習 判斷120是否在物件s列表當中 s zhiqiao lingyan yan 520 i 120 in sprint i false 修改列表 s zhiqiao qiao yan 12 i s 2 ling yan 通過索引的方式進行修改和新增第二與第三個元素為ling,ya...