list
Python内置的一种数据类型是列表:list。list是一种有序的集合,可以随时添加和删除其中的元素。
Code:
print('------------------------------------------------------')
#list
classmates = ['Michael','Bob','Tracy','Jason']
print(classmates)
print('classmates =',len(classmates)) #获取数组长度
print(classmates[0]) #第一个元素
print(classmates[1]) #第二个元素
print(classmates[2]) #第三个元素
print('------------------------------------------------------')
print(classmates[-1]) #倒数第一个元素
print(classmates[-2]) #倒数第二个元素
print(classmates[-3]) #倒数第三个元素
print('------------------------------------------------------')
a = len(classmates)-1 # 最后一个元素的索引
print(classmates[a]) # 等价于print(classmates[-1])
print('------------------------------------------------------')
print(classmates)
print(classmates[-1])
classmates.append('adm') #在末尾插入一个元素
print(classmates)
print(classmates[-1])
print('------------------------------------------------------')
print(classmates)
print(classmates[1])
classmates.insert(1,'Plada') #在指定位置插入一个元素
print(classmates)
print(classmates[1])
print('------------------------------------------------------')
print(classmates.pop()) #删除list末尾的元素
print(classmates)
print('------------------------------------------------------')
print(classmates)
print('classmates.pop(-1) :',classmates.pop(-1)) #删除指定位置的元素
print(classmates)
print('classmates.pop(1) :',classmates.pop(1))
print(classmates)
print('------------------------------------------------------')
print(classmates)
a = classmates[1] = 'Jason'
print('classmates[1] =',a)
print(classmates)
print('------------------------------------------------------')
L = ['abc',123,True]
print(len(L))
print(L[0])
print(L[1])
print(L[2])
print('------------------------------------------------------')
s = ['python','java',['asp','php'],'c++']
p = ['asp','php']
s = ['python','java',p,'c++'] #二维数组
print('p =',p)
print('s =',s)
print('p[1] =',p[1])
print('s[2][1] =',s[2][1])
print('------------------------------------------------------')
a = ['abcd','efg','hijk']
b = [a,'lmn','opq']
c = [b,'rst','uvw','xyz'] #三位数组
print('c =',c)
print('a[0] =',a[0])
print('b[0][0] =',b[0][0])
print('c[0][0][0] =',c[0][0][0])
print('------------------------------------------------------')
L = []
print('L =',len(L))
tuple
另一种有序列表叫元组:tuple。tuple和list非常类似,但是tuple一旦初始化就不能修改,比如同样是列出同学的名字:
Code:
print('------------------------------------------------------')
#tuple:一旦初始化就不能修改
classmates = ('Michael','Bob','Tracy','Jason')
print('classmates =',classmates)
t = (1,2)
print('t =',t)
r = ('a',)
print('r =',r)
print('------------------------------------------------------')
x = ('a','b',['A','B'])
print('x =',x)
x[2][0] = 'X'
x[2][1] = 'Y'
print('x =',x)
print('------------------------------------------------------')
x = ('a','b',('A','B'))
print('x =',x)
x[2][0] = 'X' #tuple数组不能修改,会报错
x[2][1] = 'Y'
print('x =',x)
TestCode:
# -*- coding: utf-8 -*-
L = [
['Apple','Google','Microsoft'],
['Java','Python','Ruby','PHP'],
['Adam','Bart','Lisa']
]
#打印Apple:
print(L[0][0])
#打印Python:
print(L[1][1])
#打印Lisa:
print(L[2][2])