Python数组与元组

一、数组(list)
(1)数组定义
subject=[‘Chinese’,‘Maths’,‘English’,‘Music’,‘Geography’,‘history’]
print(subject)–遍历数组的每一个元素

print(subject[3])–输出索引值为3的元素“Music”

print(subject(-1))
数组访问>用索引访问,索引从0开始;-1代表访问最后一个元素

print(subject[6]) 当索引越界,报错信息为index out of range

(2)数组元素添加修改与删除
1、添加元素
subject.append(“Science”)
print(subject) 在数组的最后一个元素的后面追加元素

subject.insert(2,“politics”) 在数组索引为2添加该元素
print(subject)

2、修改元素
subject[1]=‘transporatation’ 修改第一个科目元素为“transporatation”
print(subject)

3、删除元素
subject.pop() 删除末尾元素
print(subject)

subject.pop(0) 删除指定元素
print(subject)

二、Python元组数据

元组(Tuple)
元组类似与列表,元组的元素一旦定义不能修改,元组使用小括号,列表使用方括号。
country=(‘China’,‘UK’,‘US’,‘Itily’,‘Indian’)
print(country) 打印出所有的country

print(country[2]) 打印出的“US”

print(country[1:3]) 显示索引1到3的元素,不包括3

print (country[1:]) 显示索引1以后的所有元素(包括1)
print(country[:1]) 显示1之前的元素

print(len(country)) 打印显示元组长度

当元组的元素个数只有一个时,为了消除数字歧义,元组定义为 t=(4,)

score=(100,500,360,255)
print(max(score)) 显示元组中的最大值

你可能感兴趣的:(python,基础,tuple语法,Python数组)