list和元组(tuple)基本操作

复制代码
classmates = ['Michael', 'Bob', 'Tracy']
print(classmates)
print(len(classmates))
print(classmates[0])#Michael
print(classmates[-1])#Tracy
print(classmates[-3]) #Michael
#追加到末尾
classmates.append("Adam")
print(classmates)#['Michael', 'Bob', 'Tracy', 'Adam']
classmates.insert(1, 'Jack')
print(classmates)#['Michael', 'Jack', 'Bob', 'Tracy', 'Adam']
classmates.pop()
print(classmates)#['Michael', 'Jack', 'Bob', 'Tracy']
classmates.pop(1)
print(classmates)#['Michael', 'Bob', 'Tracy']
classmates[1] = 'Sarah'
print(classmates)#['Michael', 'Sarah', 'Tracy']
L = ['Apple', 123, True]
s = ['python', 'java', ['asp', 'php'], 'scheme']#二位数组
print(len(s))#4
print(s[2][0])#asp
复制代码

 

复制代码
#另一种有序列表叫元组:tuple。tuple和list非常类似,但是tuple一旦初始化就不能修改
classmates = ('Michael', 'Bob', 'Tracy')
#classmates[1] = '12'
#空tuple
t = ()
#要定义一个只有1个元素的tuple 会被认为是数学意义上的括号
t = (1)
print(t)#就是一个数
t = 10
print(t)#10
#正确定义方法 
t = (1,)

#元组嵌套list元素可以修改
t = ('a', 'b', ['A', 'B'])
t[2][0] = 'X'
t[2][1] = 'Y'
print(t)#('a', 'b', ['X', 'Y']) 
#练习
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])
复制代码

 

posted @   向往的人生  阅读(2050)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示