1. 程式人生 > >python——元組內建函式

python——元組內建函式

元組內建方法

元組tuple,我們可以把它看做是 只讀列表;

  • 列表轉換為元組: tuple=tuple(list) 例如: list=['Wjz','wjk','wz','hacker','beijing'] tuple=tuple(list) print(tuple) # 輸出 ('Wjz','wjk','wz','hacker','beijing')
  • 字典轉換為元組,元組中元素為字典的key: tuple=tuple(dict) 例如: dic={'wjz':1,'wjk':2} tuple=tuple(dic) print(tuple) # 輸出 ('wjz', 'wjk')
  • 字串轉換為元組,字串的每一個字元都為元組的元素: tuple=tuple(str) 例如: str='wjz wjk' tuple=tuple(str) print(tuple) # 輸出 ('w', 'j', 'z', ' ', 'w', 'j', 'k')

1. count(...)

T.count(value) -> integer -- return number of occurrences of value
統計指定目標在元組中的個數;
例如:
    tuple1=('wjz','wjk')
    print(tuple1.count('wjk'))    # 返回 1

2. index(...)

T.index(value, [start, [stop]]) -> integer -- return first index of value.
查詢指定目標在元組中的位置;可以指定位置範圍查詢;如果沒有指定或沒有找到,返回異常;
例如:
    tuple1=('wjz','wjk')
    print(tuple1.index('wjz'))    # 返回位置 0