Published 2021-11-26 10:41:11

Lists - 列表

创建列表

names = ['Michael', 'Bob', 'Tracy']
nums = [1, 2, 3]

也可以使用其他方法split()创建

line = 'Hello World!'
row = line.split(' ')
row # ['Hello', 'World!']

列表操作

names.append('Adam') # 在末尾添加元素
names.insert(1, 'Jack') # 在指定位置添加元素

使用+连接两个列表

s=[1,2,3]
t=[4,5,6]
s+t # [1,2,3,4,5,6]

列表索引从 0 开始

names = ['Michael', 'Bob', 'Tracy']
names[0] # Michael
names[1] # Bob
names[-1] # Tracy

使用索引覆盖元素

names[0] = 'Adam' # 修改第一个元素
names # ['Adam', 'Bob', 'Tracy']

使用len获取列表长度

len(names) # 3

使用in判断元素是否在列表中

'Adam' in names # True
'manon' in names # False

列表的循环

使用for循环遍历列表

for name in names:
    print(name)

查找索引值

names.index('Bob') # 1

移除元素

使用delremove删除元素

names.remove('Bob') # 删除第一个 Bob
del names[0] # 删除第一个元素

列表的排序

使用sort对列表进行排序

s = [10, 1, 7, 3]
s.sort()                    # [1, 3, 7, 10]
 
# Reverse order
s = [10, 1, 7, 3]
s.sort(reverse=True)        # [10, 7, 3, 1]
 
# It works with any ordered data
s = ['foo', 'bar', 'spam']
s.sort()                    # ['bar', 'foo', 'spam']

使用sorted创建新的列表,不会修改原列表

t = sorted(s)