Python 之 列表(list) - 基本操作
列表(list)是Python中最基本的数据结构,也是最常用的Python数据类型,列表的数据项不需要具有相同的类型。列表中的每个元素都分配一个数字 - 它的位置(索引)从0开始,第二个索引是1,依此类推。
#!/usr/bin/python
# Python 之 list 基本操作
# 创建列表
listexp = [] # 创建空列表, 创建非空列表:listexp = ['One', 'Two', 'Three']
listexp.append('One') # 添加元素
print(listexp) # 输出: ['One']
#添加/插入/修改/删除元素
listexp.append('Four')
print(listexp) # 输出: ['One', 'Four']
listexp.insert(1, "Two") # 插入新元素
print(listexp) # 输出: ['One', 'Two', 'Four']
listexp.insert(2, 'Three')
print(listexp) # 输出: ['One', 'Two', 'Three', 'Four']
listexp.insert(2, 'Three')
print(listexp) # 输出: ['One', 'Two', 'Three', 'Three', 'Four']
listexp.pop()
print(listexp) # 输出: ['One', 'Two', 'Three', 'Three']
print(len(listexp)) # 输出: 4
print(listexp[0]) # 输出: One
print(listexp[-1]) # 输出: Three
listexp[0] = 'one'
print(listexp) # 输出: ['one', 'Two', 'Three', 'Three']
listexp[0] = 'One'
print(listexp) # 输出: ['One', 'Two', 'Three', 'Three']
listexp.remove('Three') # 删除第一次出现的该元素
print(listexp) # 输出: ['One', 'Two', 'Three']
num = listexp.pop() # 返回最后一个元素,并从list中删除
print(num) # 输出: Three
print(listexp) # 输出:['One', 'Two']
# 其它操作
listexp.append('five')
listexp.append("Seven")
print(listexp) # 输出: ['One', 'Two', 'five', 'Seven']
listexp.sort() # 排序
print(listexp) # 输出: ['One', 'Seven', 'Two', 'five']
list2 = ['One', 1, 2, 'Six']
listexp.extend(list2) # 追加list,即合并list2到上listexp上
print(listexp) # 输出: ['One', 'Seven', 'Two', 'five', 'One', 1, 2, 'Six']
#listexp.sort() # 此时有int类型数据,再排序会报错:unorderable types: int() < str()
listexp.reverse() # 倒序
print(listexp) # 输出: ['Six', 2, 1, 'One', 'five', 'Two', 'Seven', 'One']
print(listexp[1:3]) # 分片 输出: [2, 1]
listexp.clear() # 清空列表
print(listexp) # 输出 []
浙公网安备 33010602011771号