python List
最近用python刷leetcode, 经常用python中的列表,所以总结一下
以备不时之需
List 遍历
List遍历有正序,逆序,跳跃式的遍历
- 正序遍历
example = [2, 1, 3, 4, 0] for i in range(len(example)): print example[i] #中途想改变i, 可以考虑while方式 i = 0 while i < len(example): print example[i] i += 1
- 逆序遍历
example = [2, 1, 3, 4, 0] for i in range(len(example))[::-1]: print example
- 跳跃式遍历
#步长为2 example = [2, 1, 3, 4, 0] for i in range(len(example))[::2]: print example[i]
List排序,翻转
List排序,翻转,需要注意原列表是否改变, 和排序,翻转操作函数是否返回值
-
#sort 不返回值,原列表发生改变 example=[2, 1, 3, 4, 0] example.sort() print example #sorted 返回值,但是原列表不变 example = [2, 1, 3, 4, 0] exampleCopy = sorted(example) print example print exampleCopy #reverse 不返回值,原列表发生改变 example = [2, 1, 3, 4, 0] example.reverse() print example #reversed 返回一个迭代器, 原列表不变 example = [2, 1, 3, 4, 0] exampleCopy = reversed(example) print example print exampleCopy
-
List分片赋值
List分片赋值,也是一个很强大的功能
-
example = [2, 1, 3, 4, 0] exampleOne = example[1 : 3] exampleTwo = example[:-2] exampleThree = example[::-1] #exampleOne = [1, 3] #exampleTwo = [2, 1, 3] #exampleThree = [0, 4, 3, 1, 2]
-
List pop方法
List pop方法,可以用来实现栈
-
example = [] example.append(2) example.append(1) example.append(3) example.append(4) example.append(0) while len(example) > 0: print example.pop()
-