nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(nums[2:5]) # [2, 3, 4]
print(nums[:3]) # [0, 1, 2] - from the start
print(nums[7:]) # [7, 8, 9] - to the end
print(nums[::2]) # [0, 2, 4, 6, 8] - every other item
print(nums[::-1]) # reversed copy
有两点值得牢记:
切片总是返回一个新列表。修改切片不会影响原列表。
结束索引不包含在内:nums[2:5] 取的是索引 2、3、4,不包括 5。
如何用 append、extend 和 insert 添加元素
这三个“往列表里添加”的方法作用各不相同,混用它们是常见的 bug 来源:
items = ["a", "b", "c"]
items.append("d") # add ONE item to the end
items.insert(0, "z") # insert ONE item at a specific index
items.extend(["e", "f"]) # add EACH item from another iterable
print(items)
append(x) 把 x 作为单个元素添加,即使 x 是列表也一样。items.append([1, 2]) 会把这个列表本身作为一个元素加进去。
items = ["a", "b", "c", "b", "d"]
items.remove("b") # removes the first occurrence of "b"
print(items)
last = items.pop() # removes and returns the last item
print(last, items)
second = items.pop(0) # remove and return the item at index 0
print(second, items)
如果用 remove() 删除列表中不存在的东西,Python 会抛出 ValueError。如果你需要“存在就删除”,要么先用 in 检查,要么用 try。
你也可以用 del 按索引删除:
items = [10, 20, 30, 40, 50]
del items[1]
print(items)
长度、成员检查与计数
nums = [4, 8, 15, 16, 23, 42, 16]
print(len(nums)) # 7
print(16 in nums) # True
print(nums.count(16)) # 2
print(nums.index(23)) # 4 - index of the first 23
in 是检查列表是否包含某个值的易读写法。如果你要在一个大列表上反复做这种检查,请改用集合:集合的成员检查是 O(1),而列表是 O(n)。
排序
有两种方式,选哪种很重要:
nums = [5, 2, 9, 1, 7]
# In place - modifies the list, returns None.
nums.sort()
print(nums) # [1, 2, 5, 7, 9]
# Returns a new sorted list, leaves the original alone.
original = [5, 2, 9, 1, 7]
sorted_nums = sorted(original)
print(sorted_nums, original)