1. 程式人生 > >python-元組方法(tulpe)知識整理

python-元組方法(tulpe)知識整理

beijing print for env bject jin typeerror art 列表

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __author__:anxu.qi
# Date:2018/11/21

################################## 元組 ###############################
# 元組和列表幾乎是一樣的
# 列表是可以進行修改的,元組是不能修改的

name_list = ("beijing","shanghai","jinan","shandong")
## 索引
print(name_list[0])
# beijing

## len
print(len(name_list))
# 4

## 切片
print(name_list[0:2])
# (‘beijing‘, ‘shanghai‘)

## for 循環
for i in name_list:
print(i)
"""
beijing
shanghai
jinan
shandong
"""
################################## 刪除元組元素報錯 ###############################
name_list = ("beijing","shanghai","jinan","shandong")
# del name_list[0]
# TypeError: ‘tuple‘ object doesn‘t support item deletion (說的是“tuple”對象不支持刪除項)


################################## count 統計個數 ###############################
# def count(self, value):
# 統計元素個數
name_list = ("beijing","shanghai","jinan","shandong","beijing")
print(name_list.count("beijing"))
# 2


################################## index 獲取索引 ###############################
# def index(self, value, start=None, stop=None):
# 獲取指定元素的下標位置
name_list = ("beijing","shandong","shanghai","jinan","shandong")
print(name_list.index(‘shandong‘)) # 獲取的下標只能從左往右
# 1


################################## 元組 ###############################


python-元組方法(tulpe)知識整理