# 【python基础】7-列表

2018-02-27 11:14:30来源:https://www.jianshu.com/p/1e2d44b8d060作者:王诗翔人点击

``>>> vowels = ['a', 'e', 'i', 'o', 'u']>>> vowels['a', 'e', 'i', 'o', 'u']>>> vowels[0]'a'>>> vowels[2]'i'>>> vowels[10]Traceback (most recent call last):  File "<stdin>", line 1, in <module>IndexError: list index out of range>>> even_numbers = list(range(2, 11, 2))>>> even_numbers[2, 4, 6, 8, 10]>>> even_numbers[-1]10>>> even_numbers[-2]8>>> even_numbers[-15]Traceback (most recent call last):  File "<stdin>", line 1, in <module>IndexError: list index out of range``

``>>> student = ['learnbyexample', 2016, 'Linux, Vim, Python']>>> print(student)['learnbyexample', 2016, 'Linux, Vim, Python']>>> list_2D = [[1, 3, 2, 10], [1.2, -0.2, 0, 2]]>>> list_2D[0][0]1>>> list_2D[1][0]1.2``

Python文档 - 列表

stackoverflow - 解释切片符号
``>>> books = ['Harry Potter', 'Sherlock Holmes', 'To Kill a Mocking Bird']>>> books[2] = "Ender's Game">>> print(books)['Harry Potter', 'Sherlock Holmes', "Ender's Game"]>>> prime = [2, 3, 5, 7, 11]>>> prime[2:4][5, 7]>>> prime[:3][2, 3, 5]>>> prime[3:][7, 11]>>> prime[-1]11>>> prime[-1:] # 注意和上一个操作的不同[11]>>> prime[-2:][7, 11]>>> prime[::1][2, 3, 5, 7, 11]>>> prime[::2][2, 5, 11]>>> prime[3:1:-1][7, 5]>>> prime[::-1][11, 7, 5, 3, 2]>>> prime[:][2, 3, 5, 7, 11]``

`start``stop`值相同在被程序自动生成时很有用

``>>> nums = [1.2, -0.2, 0, 2]>>> nums[0:0][]>>> nums[2:2][]>>> nums[-1:-1][]>>> nums[21:21][]``

``>>> nums = [1.2, -0.2, 0, 2]>>> nums[:2] = [1]>>> nums[1, 0, 2]>>> nums = [1.2, -0.2, 0, 2, 4, 23]>>> nums[:5:2] = [1, 4, 3]>>> nums[1, -0.2, 4, 2, 3, 23]>>> nums = [1, 2, 3, 23]>>> nums[::-1] = [1, 4, 5, 2]>>> nums[2, 5, 4, 1]``

``>>> id(nums)140598790579336>>> nums[:] = [1, 2, 5, 4.3]>>> nums[1, 2, 5, 4.3]>>> id(nums)140598790579336# 不使用索引[:]则会改变id>>> nums = [1.2, -0.2, 0, 2]>>> id(nums)140598782943752# 译者注：这应当是另外分配了一个新的地址和变量，然后对当前存在的进行了覆盖``

Python中的变量包含对象的引用

id()函数返回一个对象的“唯一标识符”

``>>> a = 5>>> id(a)10105952>>> a = 10>>> id(a)10106112>>> b = a>>> id(b)10106112>>> b = 4>>> b4>>> a10>>> id(b)10105920``

``>>> a = [1, 2, 5, 4.3]>>> a[1, 2, 5, 4.3]>>> b = a>>> b[1, 2, 5, 4.3]>>> id(a)140684757120264>>> id(b)140684757120264>>> b[0] = 'xyz'>>> b['xyz', 2, 5, 4.3]>>> a['xyz', 2, 5, 4.3]``

``>>> prime = [2, 3, 5, 7, 11]>>> b = prime[:]>>> id(prime)140684818101064>>> id(b)140684818886024>>> b[0] = 'a'>>> b['a', 3, 5, 7, 11]>>> prime[2, 3, 5, 7, 11]>>> list_2D = [[1, 3, 2, 10], [1.2, -0.2, 0, 2]]>>> a = list_2D[:]>>> id(list_2D)140684818102344>>> id(a)140684818103048>>> a[[1, 3, 2, 10], [1.2, -0.2, 0, 2]]>>> a[0][0] = 'a'>>> a[['a', 3, 2, 10], [1.2, -0.2, 0, 2]]>>> list_2D[['a', 3, 2, 10], [1.2, -0.2, 0, 2]]``

``>>> import copy>>> list_2D = [[1, 3, 2, 10], [1.2, -0.2, 0, 2]]>>> c = copy.deepcopy(list_2D)>>> c[0][0] = 'a'>>> c[['a', 3, 2, 10], [1.2, -0.2, 0, 2]]>>> list_2D[[1, 3, 2, 10], [1.2, -0.2, 0, 2]]``

``>>> books = []>>> books[]>>> books.append('Harry Potter')>>> books['Harry Potter']>>> even_numbers[2, 4, 6, 8, 10]>>> even_numbers += [12, 14, 16, 18, 20]>>> even_numbers[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]>>> even_numbers = [2, 4, 6, 8, 10]>>> even_numbers.extend([12, 14, 16, 18, 20])>>> even_numbers[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]>>> a = [[1, 3], [2, 4]]>>> a.extend([[5, 6]])>>> a[[1, 3], [2, 4], [5, 6]]``

``>>> prime = [2, 3, 5, 7, 11]>>> prime.pop()11>>> prime[2, 3, 5, 7]>>> prime.pop(0)2>>> prime[3, 5, 7]>>> list_2D = [[1, 3, 2, 10], [1.2, -0.2, 0, 2]]>>> list_2D[0].pop(0)1>>> list_2D[[3, 2, 10], [1.2, -0.2, 0, 2]]>>> list_2D.pop(1)[1.2, -0.2, 0, 2]>>> list_2D[[3, 2, 10]]``

``>>> nums = [1.2, -0.2, 0, 2, 4, 23]>>> del nums[1]>>> nums[1.2, 0, 2, 4, 23]# 也可以使用切片>>> del nums[1:4]>>> nums[1.2, 23]>>> list_2D = [[1, 3, 2, 10], [1.2, -0.2, 0, 2]]>>> del list_2D[0][1]>>> list_2D[[1, 2, 10], [1.2, -0.2, 0, 2]]>>> del list_2D[0]>>> list_2D[[1.2, -0.2, 0, 2]]``

``>>> prime = [2, 3, 5, 7, 11]>>> prime.clear()>>> prime[]``

``>>> even_numbers = [2, 4, 6, 8, 10]>>> even_numbers.remove(8)>>> even_numbers[2, 4, 6, 10]>>> even_numbers.remove(12)Traceback (most recent call last):  File "<stdin>", line 1, in <module>ValueError: list.remove(x): x not in list``

``>>> books = ['Harry Potter', 'Sherlock Holmes', 'To Kill a Mocking Bird']>>> books.insert(2, "The Martian")>>> books['Harry Potter', 'Sherlock Holmes', 'The Martian', 'To Kill a Mocking Bird']``

``>>> even_numbers = [2, 4, 6, 8, 10]>>> even_numbers.index(6)2>>> even_numbers.index(12)Traceback (most recent call last):  File "<stdin>", line 1, in <module>ValueError: 12 is not in list``

``>>> prime = [2, 3, 5, 7, 11]>>> 3 in primeTrue>>> 13 in primeFalse``

``>>> a = [1, 5.3, 321, 0, 1, 2]>>> a.sort()>>> a[0, 1, 1, 2, 5.3, 321]>>> a = [1, 5.3, 321, 0, 1, 2]>>> a.sort(reverse=True)>>> a[321, 5.3, 2, 1, 1, 0]``

lambda表达式在比如传递自定义单个表达式、基于第二个字母进行排序中很有用

``>>> words = ['fuliginous', 'crusado', 'morello', 'irk', 'seam']>>> words.sort(key=len)>>> words['irk', 'seam', 'crusado', 'morello', 'fuliginous']>>> words.sort(key=lambda x: x[1])>>> words['seam', 'morello', 'irk', 'crusado', 'fuliginous']``

``>>> nums = [-1, 34, 0.2, -4, 309]>>> nums_desc = sorted(nums, reverse=True)>>> nums_desc[309, 34, 0.2, -1, -4]>>> sorted(nums, key=abs)[0.2, -1, -4, 34, 309]``

`min``max`

``>>> a = [321, 899.232, 5.3, 2, 1, -1]>>> min(a)-1>>> max(a)899.232``

``>>> nums = [15, 99, 19, 382, 43, 19]>>> nums.count(99)1>>> nums.count(19)2>>> nums.count(23)0``

``>>> prime = [2, 3, 5, 7, 11]>>> id(prime)140684818102088>>> prime.reverse()>>> prime[11, 7, 5, 3, 2]>>> id(prime)140684818102088>>> a = [1, 5.3, 321, 0, 1, 2]>>> id(a)140684818886024>>> a = a[::-1]>>> a[2, 1, 0, 321, 5.3, 1]>>> id(a)140684818102664``

len函数获取列表的大小
``>>> prime[2, 3, 5, 7, 11]>>> len(prime)5>>> s = len(prime) // 2>>> prime[:s][2, 3]>>> prime[s:][5, 7, 11]``

``>>> a[321, 5.3, 2, 1, 1, 0]>>> sum(a)330.3``

all和any函数
``>>> conditions = [True, False, True]>>> all(conditions)False>>> any(conditions)True>>> conditions[1] = True>>> all(conditions)True>>> a = [321, 5.3, 2, 1, 1, 0]>>> all(a)False>>> any(a)True``

``>>> prime[2, 3, 5, 7, 11]>>> a = [4, 2]>>> prime == aFalse>>> prime == [2, 3, 5, 11, 7]False>>> prime == [2, 3, 5, 7, 11]True``

Python文档 - 列表详情
Python文档 - 集合

``#!/usr/bin/python3numbers = [2, 12, 3, 25, 624, 21, 5, 9, 12]odd_numbers  = []even_numbers = []for num in numbers:    odd_numbers.append(num) if(num % 2) else even_numbers.append(num)print("numbers:      {}".format(numbers))print("odd_numbers:  {}".format(odd_numbers))print("even_numbers: {}".format(even_numbers))``

``\$ ./list_looping.pynumbers:      [2, 12, 3, 25, 624, 21, 5, 9, 12]odd_numbers:  [3, 25, 21, 5, 9]even_numbers: [2, 12, 624, 12]``

``#!/usr/bin/python3north_dishes = ['Aloo tikki', 'Baati', 'Khichdi', 'Makki roti', 'Poha']print("My favorite North Indian dishes:")for idx, item in enumerate(north_dishes):    print("{}. {}".format(idx + 1, item))``

Python文档 - enumerate
``\$ ./list_looping_enumeration.pyMy favorite North Indian dishes:1. Aloo tikki2. Baati3. Khichdi4. Makki roti5. Poha``

``>>> north_dishes = ['Aloo tikki', 'Baati', 'Khichdi', 'Makki roti', 'Poha']>>> for idx, item in enumerate(north_dishes, start=1):...     print(idx, item, sep='. ')...1. Aloo tikki2. Baati3. Khichdi4. Makki roti5. Poha``

Python文档 - zip
``>>> odd = [1, 3, 5]>>> even = [2, 4, 6]>>> for i, j in zip(odd, even):...     print(i + j)...3711``

``#!/usr/bin/python3import timenumbers = list(range(1,100001))fl_square_numbers = []# 引用时间t0 = time.perf_counter()# ------------ for 循环 ------------for num in numbers:    fl_square_numbers.append(num * num)# 引用时间t1 = time.perf_counter()# ------- 列表推导式 -------lc_square_numbers = [num * num for num in numbers]# 执行结果t2 = time.perf_counter()fl_time = t1 - t0lc_time = t2 - t1improvement = (fl_time - lc_time) / fl_time * 100print("Time with for loop:           {:.4f}".format(fl_time))print("Time with list comprehension: {:.4f}".format(lc_time))print("Improvement:                  {:.2f}%".format(improvement))if fl_square_numbers == lc_square_numbers:    print("/nfl_square_numbers and lc_square_numbers are equivalent")else:    print("/nfl_square_numbers and lc_square_numbers are NOT equivalent")``

``\$ ./list_comprehension.pyTime with for loop:           0.0142Time with list comprehension: 0.0062Improvement:                  56.36%fl_square_numbers and lc_square_numbers are equivalent``

``# 使用在列表推导式中使用if-else条件语句numbers = [2, 12, 3, 25, 624, 21, 5, 9, 12]odd_numbers  = []even_numbers = [][odd_numbers.append(num) if(num % 2) else even_numbers.append(num) for num in numbers]#　或者一种更简单和易读的方式numbers = [2, 12, 3, 25, 624, 21, 5, 9, 12]odd_numbers  = [num for num in numbers if num % 2]even_numbers = [num for num in numbers if not num % 2]``

zip示例
``>>> p = [1, 3, 5]>>> q = [3, 214, 53]>>> [i+j for i,j in zip(p, q)][4, 217, 58]>>> [i*j for i,j in zip(p, q)][3, 642, 265]``

``>>> sum(i*j for i,j in zip(p, q))910``

Python文档 - 列表推导式
Python列表推导式：可视化解释

Python文档 - perf_counter

Python文档 - timeit

``>>> b = input('Enter strings separated by space: ').split()Enter strings separated by space: foo bar baz>>> b['foo', 'bar', 'baz']>>> nums = [int(n) for n in input('Enter numbers separated by space: ').split()]Enter numbers separated by space: 1 23 5>>> nums[1, 23, 5]>>> ip_str = input('Enter prime numbers separated by comma: ')Enter prime numbers separated by comma: 3,5,7>>> primes = [int(n) for n in ip_str.split(',')]>>> primes[3, 5, 7]``

``>>> import random>>> a = [4, 5, 2, 76]>>> random.choice(a)76>>> random.choice(a)4``

``>>> random.shuffle(a)>>> a[5, 2, 76, 4]``

``>>> random.sample(a, k=3)[76, 2, 5]>>> random.sample(range(1000), k=5)[68, 203, 15, 757, 580]``

``>>> nums = [1, 3, 6, -12, 1.2, 3.14]>>> random.shuffle(nums)>>> nums_iter = iter(nums)>>> print(next(nums_iter))3.14>>> print(next(nums_iter))1.2>>> for n in nums_iter:...     print(n)...13-126>>> print(next(nums_iter))Traceback (most recent call last):  File "<stdin>", line 1, in <module>StopIteration``

Python文档 - random获取更多信息
3.6版本更新 - random.choices

Python文档 - next