3.1列表是什么
使用方括号([])来标识列表
# encoding=utf-8
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)
['trek', 'cannondale', 'redline', 'specialized']
3.2访问,修改,添加,删除列表元素
看代码总是最直接的
# encoding=utf-8
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)
print(bicycles[0] + "," + bicycles[1])
# 访问最后一个元素[-1],索引-2访问倒数第二个元素 java没有
print(bicycles[-1] + "," + bicycles[-2])
# IndexError: list index out of range
# print(bicycles[-5])
# print(bicycles[4])
bicycles[0] = 'car'
print(bicycles)
ages = []
print(ages)
# 列表尾部添加
ages.append(10)
ages.append(30)
ages.append(45)
print(ages)
# 指定位置添加
ages.insert(0, 1)
print(ages)
# 删除指定位置元素
del ages[-1]
del ages[0]
print(ages)
# 从队尾弹出元素
age = ages.pop()
print(ages.__str__() + "," + str(age))
ages.append(50)
ages.append(60)
ages.append(70)
# 从指定位置弹出元素
age = ages.pop(-2)
print(ages.__str__() + "," + str(age))
age_10 = 10
ages.append(age_10)
# 删除指定值,只会删除第一个满足条件的值,如果没有找到则会抛错
ages.remove(age_10)
print(ages)
# ValueError: list.remove(x): x not in list
# ages.remove(100000)
['trek', 'cannondale', 'redline', 'specialized']
trek,cannondale
specialized,redline
['car', 'cannondale', 'redline', 'specialized']
[]
[10, 30, 45]
[1, 10, 30, 45]
[10, 30]
[10],30
[10, 50, 70],60
[50, 70, 10]
3.3 组织列表
列表函数:sort(),
通用函数:sorted(),len()
# encoding=utf-8
# sort列表排序
names = ['zhang', 'wang', 'shi', 'chu']
names.sort()
print(names)
# sort列表逆向排序
names.sort(reverse=True)
print(names)
# sorted()函数返回排好序的列表,但不改变原始列表顺序
asc_names = sorted(names)
print(str(names) + "," + str(asc_names))
desc_names = sorted(names, reverse=True)
print(str(names)+","+str(desc_names))
# 反转列表元素
names.append('tian')
names.reverse()
print(names)
# 查询列表长度
print(len(names))
print(names.__len__())
['chu', 'shi', 'wang', 'zhang']
['zhang', 'wang', 'shi', 'chu']
['zhang', 'wang', 'shi', 'chu'],['chu', 'shi', 'wang', 'zhang']
['zhang', 'wang', 'shi', 'chu'],['zhang', 'wang', 'shi', 'chu']
['tian', 'chu', 'shi', 'wang', 'zhang']
5
5