列表通常包含多个元素,所以在命名的时候会使用一个复数的形式

List

  1. motorcycles = ['honda', 'yamaha', 'suzuki']
  2. print(motorcycles)
  3. # ['honda', 'yamaha', 'suzuki']
  4. # 末尾添加 append
  5. motorcycles.append('ducati')
  6. print(motorcycles)
  7. # ['honda', 'yamaha', 'suzuki', 'ducati']
  8. # 插入 insert
  9. motorcycles.insert(0, 'ducati')
  10. print(motorcycles)
  11. # ['ducati', 'honda', 'yamaha', 'suzuki', 'ducati']
  12. # 两个list相加 +相当于extend
  13. >>> a = [1]
  14. >>> b = [2]
  15. >>> a+b
  16. [1, 2]
  17. >>> a.append(b)
  18. >>> a
  19. [1, [2]]
  20. >>> a.extend(b)
  21. >>> a
  22. [1, [2], 2]

  1. motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati', 'suzuki', 'jialing', 'lingmu']
  2. print(motorcycles)
  3. # 只需要删除 del
  4. del motorcycles[0]
  5. print(motorcycles)
  6. # 删除同时需要拿到元素值 pop
  7. motorcycles.pop(0)
  8. print(motorcycles)
  9. # pop默认是删除并拿到末尾元素,也可以指定位置 motorcycles.pop(0)
  10. motorcycles.pop()
  11. print(motorcycles)
  12. # 根据值删除 remove,只删除第一个指定的值,如果删除多个,需要循环
  13. motorcycles.remove('suzuki')
  14. print(motorcycles)
  1. ['honda', 'yamaha', 'suzuki', 'ducati', 'suzuki', 'jialing', 'lingmu']
  2. ['yamaha', 'suzuki', 'ducati', 'suzuki', 'jialing', 'lingmu']
  3. ['suzuki', 'ducati', 'suzuki', 'jialing', 'lingmu']
  4. ['suzuki', 'ducati', 'suzuki', 'jialing']
  5. ['ducati', 'suzuki', 'jialing']

  1. motorcycles = ['honda', 'yamaha', 'suzuki']
  2. print(motorcycles)
  3. motorcycles[0] = 'ducati'
  4. print(motorcycles)
  1. ['honda', 'yamaha', 'suzuki']
  2. ['ducati', 'yamaha', 'suzuki']

  • 取任意一个
  • 取最后一个
  1. bicyclkes = ['trek', 'cannondale', 'redline', 'specialized']
  2. print(bicyclkes[0])
  3. print(bicyclkes[-1])
  1. trek
  2. specialized

组织列表

排序

  • list.sort():改变原列表
  • sorted(list):生成一份拷贝,不改变原列表
  1. # sort 改变原列表
  2. cars = ['bmw', 'audi', 'toyota', 'sabaru', 'mazida']
  3. cars.sort()
  4. print(cars)
  5. cars.sort(reverse=True)
  6. print(cars)
  7. -- output
  8. ['audi', 'bmw', 'mazida', 'sabaru', 'toyota']
  9. ['toyota', 'sabaru', 'mazida', 'bmw', 'audi']
  1. # sorted 生成一份拷贝,不改变原列表
  2. cars = ['bmw', 'audi', 'toyota', 'sabaru']
  3. print("Here is the original list:")
  4. print(cars)
  5. print("\nHere is the sorted list:")
  6. print(sorted(cars))
  7. -- output
  8. Here is the original list:
  9. ['bmw', 'audi', 'toyota', 'sabaru']
  10. Here is the sorted list:
  11. ['audi', 'bmw', 'sabaru', 'toyota']
  1. # 倒着打印列表
  2. cars = ['bmw', 'audi', 'toyota', 'sabaru']
  3. cars.reverse()
  4. print(cars)
  5. # 确定列表长度
  6. print(len(cars))
  7. -- output
  8. ['sabaru', 'toyota', 'audi', 'bmw']
  9. 4

去重

  1. 使用set
  2. 使用itertools
  3. 不改变原顺序
  1. # 1. set()
  2. ids = [1,4,3,3,4,2,3,4,5,6,1]
  3. ids = list(set(ids))
  4. # 2. 使用itertools
  5. import itertools
  6. ids = [1,4,3,3,4,2,3,4,5,6,1]
  7. it = itertools.groupby(ids)
  8. for k, g in it:
  9. print k
  10. # 3. 不改变原顺序
  11. In [5]: ids = [1,4,3,3,4,2,3,4,5,6,1]
  12. In [6]: func = lambda x,y: x if y in x else x + [y]
  13. In [7]: reduce(func, [[], ] + ids)
  14. Out[7]: [1, 4, 3, 2, 5, 6]

展平元素

例如:[[1,2,3], [4,5,6]] -> [1,2,3,4,5,6]

  1. 循环 ```python

    The list of lists

    [[0, 1, 2, 3], [0, 1, 2, 3, 4, 5, 6]]

    list_of_lists = [range(4), range(7)] flattened_list = []

flatten the list

for x in list_of_lists: for y in x: flattened_list.append(y)

  1. 2. 列表
  2. ```python
  3. #The list of lists
  4. list_of_lists = [range(4), range(7)]
  5. #flatten the lists
  6. flattened_list = [y for x in list_of_lists for y in x]
  1. extend

获取出现次数最多的元素

  1. 使用collections
  1. from collections import Counter
  2. a = [['PER', 0, 1], ['PER', 5, 8], ['ORG', 0, 3]]
  3. Counter([x[0] for x in a])
  4. -- output
  5. Counter({'PER': 2, 'ORG': 1})
  1. 使用numpy
  1. import numpy
  2. num=1000000
  3. lst = np.random.randint(num / 10, size=num)
  4. dict(zip(*np.unique(lst, return_counts=True)))
  1. 使用list.count()
  1. import numpy
  2. num=1000000
  3. lst = np.random.randint(num / 10, size=num)
  4. dic = {}
  5. for i in lst:
  6. dic[i] = lst.count(i)
  1. 获取字典中value的最大值所对应的键的方法
  1. lt = ['小马', '小敏', '小乔', '小敏', '小杜', '小杜', '小孟', '小敏']
  2. print(max(lt, key=lt.count)

查找指定值在列表中的位置

  1. # [].index 返回列表中第一次出现的位置
  2. lt = ['小马', '小敏', '小乔', '小敏', '小杜', '小杜', '小孟', '小敏']
  3. lt.index('小敏')
  4. -- output
  5. 1

从列表中随机挑选N个元素

sample(population, k)从population中取样,一次取k个,返回一个k长的列表。

  1. from random import sample
  2. a = [3, 4, 5, 6]
  3. sample(a, 2)
  4. -- output
  5. [5, 3]

遍历列表

for 循环遍历

  1. magicians = ['alice', 'david', 'carolina']
  2. for magician in magicians:
  3. print(magician)
  1. alice
  2. david
  3. carolina

指定索引遍历

  1. l = [2,7,11,15]
  2. for index,value in enumerate(l):
  3. print index,value

创建数值列表

  1. # 生成一系列数字
  2. for value in range(1, 5):
  3. print(value)
  4. # 使用range()创建数字列表
  5. numbers = list(range(1, 6))
  6. print("numbers =", numbers)
  7. # 指定步长
  8. even_numbers = list(range(2, 11, 2))
  9. print("even_numbers =", even_numbers)
  1. 1
  2. 2
  3. 3
  4. 4
  5. numbers = [1, 2, 3, 4, 5]
  6. even_numbers = [2, 4, 6, 8, 10]

对数字列表执行统计计算

  1. digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  2. print("min_digits =", min(digits))
  3. print("max_digits =", max(digits))
  4. print("sum_digits =", sum(digits))
  1. min_digits = 1
  2. max_digits = 10
  3. sum_digits = 55

列表解析

列表解析是定义一个表达式,生成的值存入到列表里

  1. squares = [value ** 2 for value in range(1, 11)]
  2. print(squares)
  1. [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

使用列表的一部分

切片

  1. players = ['charles', 'martina', 'michael', 'florence', 'eli']
  2. print("players[0:3] =", players[0:3])
  3. print("players[:4] =", players[:4])
  4. print("players[2:] =", players[2:])
  5. print("players[-3:] =", players[-3:])
  1. players[0:3] = ['charles', 'martina', 'michael']
  2. players[:4] = ['charles', 'martina', 'michael', 'florence']
  3. players[2:] = ['michael', 'florence', 'eli']
  4. players[-3:] = ['michael', 'florence', 'eli']

复制列表

直接赋值friends_foods=my_foods只是让两个变量同时指向一个对象,对任意一个变量的修改,都会引起内容的修改。

  1. my_foods = ['pizza', 'falafel', 'carrot cake']
  2. friends_foods = my_foods[:]
  3. print("My favorite foods are:")
  4. print(my_foods)
  5. print("\nMy friends's favorite foods are:")
  6. print(friends_foods)
  7. my_foods.append('cannoli')
  8. friends_foods.append('ice cream')
  9. print("After add, My favorite foods are:")
  10. print(my_foods)
  11. print("\nAfter add, My friends's favorite foods are:")
  12. print(friends_foods)
  1. My favorite foods are:
  2. ['pizza', 'falafel', 'carrot cake']
  3. My friends's favorite foods are:
  4. ['pizza', 'falafel', 'carrot cake']
  5. After add, My favorite foods are:
  6. ['pizza', 'falafel', 'carrot cake', 'cannoli']
  7. After add, My friends's favorite foods are:
  8. ['pizza', 'falafel', 'carrot cake', 'ice cream']

元组

元组是不可变的列表,切片与列表是一致的。

字典 dict

创建/增加

  1. # 可以在最后一个键值对后也添加逗号,方便以后继续添加
  2. >>> favorite_languages = {
  3. ... 'jen':'python',
  4. ... 'sarah':'c',
  5. ... 'edward':'ruby',
  6. ... 'phil':'python',
  7. ... }
  8. >>> favorite_languages
  9. {'sarah': 'c', 'edward': 'ruby', 'jen': 'python', 'phil': 'python'}
  10. # 从两个列表创建字典
  11. >>> a=['a', 'b', 'c']
  12. >>> b=3
  13. >>> c=dict(zip(a, range(b)))
  14. >>> c
  15. {'a': 0, 'b': 1, 'c': 2}

根据key或value排序

  1. >>> a = {'a':1, 'b':3, 'c':2}
  2. >>> a
  3. {'a': 1, 'b': 3, 'c': 2}
  4. # 根据key排序,默认为顺序
  5. >>> sorted(a.items(), key=lambda item: item[0])
  6. [('a', 1), ('b', 3), ('c', 2)]
  7. # 根据value排序,倒序
  8. >>> sorted(a.items(), key=lambda item: item[1], reverse=True)
  9. [('b', 3), ('c', 2), ('a', 1)]

返回默认key的字典 defaultdict

defaultdict 超级好用,他无需判断某个key是否在字典里,当不在时,会自动加入,对应的value,在不同的类型时,有不同的默认值:

  • int - 0
  • list - []
  • set - set()
  • str - 空字符串 ```python

    from collections import defaultdict d1 = dict() d2 = defaultdict(list) print(d1[‘a’]) Traceback (most recent call last): File ““, line 1, in KeyError: ‘a’

print(d2[‘a’]) []

d3 = defaultdict(int) d3[‘a’] 0 d2[‘a’].append(1) d2 defaultdict(, {‘a’: [1]}) ```

update

  1. #!/usr/bin/python
  2. >>> d1 = {'Name': 'Zara', 'Age': 7}
  3. >>> d2 = {'Sex': 'female', 'Name': 'Sarah' }
  4. >>>
  5. >>> d1.update(d2)
  6. >>> print("Value : %s" % d1)
  7. Value : {'Name': 'Sarah', 'Age': 7, 'Sex': 'female'}

删除

  1. d = {"name":"wasan", "age":14}
  2. del d["name"]
  3. -- 结果
  4. {'age': 14}

遍历

  1. 迭代keys map.keys()
  2. 迭代values map.values()
  3. 同时迭代key和value map.items()
  4. 按顺序遍历字典的key sorted(map.keys) ```python

    a = {“name”:”zhangsan”, “age”:18, “gender”:”male”} a.keys() [‘gender’, ‘age’, ‘name’]

a.values() [‘male’, 18, ‘zhangsan’]

a.items() [(‘gender’, ‘male’), (‘age’, 18), (‘name’, ‘zhangsan’)]

for k in a.keys(): … print(k, a[k]) … (‘gender’, ‘male’) (‘age’, 18) (‘name’, ‘zhangsan’)

for k,v in a.items(): … print(k,v) … (‘gender’, ‘male’) (‘age’, 18) (‘name’, ‘zhangsan’)

sorted(a.keys()) [‘age’, ‘gender’, ‘name’] ```