Python从人门到实践(五)列表
创建列表与使用其中元素
Python内置的一种数据类型是列表:list。 列表是由按照特定顺序排列的元素组成。 可以随时添加和删除其中的元素。 创建一个list
name=['trek','cannondale','redline','specialized']
print(name)
输出:
['trek', 'cannondale', 'redline', 'specialized']
list里面的元素的数据类型也可以不同
L = ['Apple', 123, True]
list元素也可以是另一个list
p = ['asp', 'php']
s = ['python', 'java', p, 'scheme']
print(s)
print(len(s))
输出:
['python', 'java', ['asp', 'php'], 'scheme']
4
访问与使用list的内容
#索引从0开始
name=['trek','cannondale','redline','specialized']
print(name[0])
print(name[2])
#索引-1,直接返回最后一个元素(适用于不知道列表长度的情况)
print(name[-1])
输出:
trek
redline
specialized
修改添加删除list元素
修改 直接赋值给对应的索引位置
name=['trek','cannondale','redline','specialized']
#修改列表元素
#直接赋值给对应的索引位置
print(name)
name[1]='xxx'
print(name)
输出:
['trek', 'cannondale', 'redline', 'specialized']
['trek', 'xxx', 'redline', 'specialized']
添加 append() insert()
name=['trek','cannondale','redline','specialized']
#添加到末尾 append()
name.append('lwx')
print(name)
#插入insert()
name.insert(1,'xxx')
print(name)
输出:
['trek', 'cannondale', 'redline', 'specialized', 'lwx']
['trek', 'xxx', 'cannondale', 'redline', 'specialized', 'lwx']
删除与弹出 del()
#del删除
name=['trek','cannondale','redline','specialized']
print(name)
del name[0]
print(name)
输出:
['trek', 'cannondale', 'redline', 'specialized']
['cannondale', 'redline', 'specialized']
注意两种删除方式的使用方法不同
pop()可以删除任意位置的元素
#pop弹出
name=['trek','cannondale','redline','specialized']
print(name)
popped_name_last=name.pop() #将最后一个元素拿出来
print(name)
print(popped_name_last)
popped_name_first=name.pop(0)#将指定的元素拿出来
print(name)
print(popped_name_first)
输出:
['trek', 'cannondale', 'redline', 'specialized']
['trek', 'cannondale', 'redline']
specialized
['cannondale', 'redline']
trek
remove()根据值删除元素 但remove只删除第一个指定的值,如多次出现需要循环来确保每个值都删除
name=['trek','cannondale','redline','specialized']
print(name)
name.remove('trek')
print(name)
输出:
['trek', 'cannondale', 'redline', 'specialized']
['cannondale', 'redline', 'specialized']
组织list列表
sort()按首字母永久排序
name=['trek','cannondale','redline','specialized']
print(name)
name.sort()
print(name)
#反向排序
name.sort(reverse=True)
print(name)
输出:
['trek', 'cannondale', 'redline', 'specialized']
['cannondale', 'redline', 'specialized', 'trek']
['trek', 'specialized', 'redline', 'cannondale']
sorted()临时排序 不影响列表的原始排列顺序
name=['trek','cannondale','redline','specialized']
print('here is(original):')
print(name)
print('here is(sorted):')
print(sorted(name))
print('now here is(again):')
print(name)
#反向排序另一种方法
name.reverse()
print(name)
输出:
here is(original):
['trek', 'cannondale', 'redline', 'specialized']
here is(sorted):
['cannondale', 'redline', 'specialized', 'trek']
now here is(again):
['trek', 'cannondale', 'redline', 'specialized']
['specialized', 'redline', 'cannondale', 'trek']
|