list / tuple / dict(I)
注意区分list和tuple
简化创建list/tuple
# list or tuple
[ o.dosomething for o in objects if True ]
或者
[ dosomething if x... else ... for x in Xs]
生成浮点数list
range只支持int,对于浮点数建议是用numpy的arange
>>> import numpy as np
>>> np.arange(0,1,0.1)
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
特别注意:用range()
方法计算得出的list会存在浮点计算的问题,例如:
>>>[x * 0.1 for x in range(0, 10)]
...[0.0, 0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6000000000000001, 0.7000000000000001, 0.8, 0.9]
named tuple
For example, it is common to represent a point, for example as a tuple (x, y). This leads to code like the following:
pt1 = (1.0, 5.0)
pt2 = (2.5, 1.5)
from math import sqrt
line_length = sqrt((pt1[0]-pt2[0])**2 + (pt1[1]-pt2[1])**2)
Using a named tuple it becomes more readable:
from collections import namedtuple
Point = namedtuple('Point', 'x y')
pt1 = Point(1.0, 5.0)
pt2 = Point(2.5, 1.5)
from math import sqrt
line_length = sqrt((pt1.x-pt2.x)**2 + (pt1.y-pt2.y)**2)
还可以用来“反射”
判断list/tuple是否为空
直接判断其是否为 True(或False即可) 这种做法更“Pythonic”,对于用len(a)==0来判断,不是被推荐的。 查看Python文档说明
a = [] # a = ()
if a:
print("List is not empty.")
else:
print("List is empty.")
>>> if not (None or False or 0 or 0.0 or 0j or '' or () or [] or {}):
... print('False')
False
list() OR [] ?
原文
[] is faster than list(),同理()和tuple()、{}和dict()
>>> timeit.timeit('[]', number=10**7)
0.400970278520802
>>> timeit.timeit('list()', number=10 ** 7)
1.977615857740119
>>> timeit.timeit('()', number=10**7)
0.32171692848272926
>>> timeit.timeit('tuple()', number=10**7)
1.4221802492102285
list的append 和 extend方法的区别
Appends object at end.
x = [1, 2, 3]
x.append([4, 5])
print (x) # gives you: [1, 2, 3, [4, 5]]
Extends list by appending elements from the iterable.
x = [1, 2, 3]
x.extend([4, 5])
print (x) # gives you: [1, 2, 3, 4, 5]
获取list中某元素的数量
>>> [1, 2, 3, 4, 1, 4, 1].count(1)
3
If you are using Python 2.7 or 3 and you want number of occurrences for each element:
>>> from collections import Counter
>>> z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
>>> Counter(z)
Counter({'blue': 3, 'red': 2, 'yellow': 1})
排列组合list中的元素
import itertools
Permutation (order matters):
>>> print (list(itertools.permutations([1,2,3,4], 2)))
[(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]
Combination (order does NOT matter):
>>> print(list(itertools.combinations('123', 2)))
[('1', '2'), ('1', '3'), ('2', '3')]
Cartesian product (with several iterables):
>>> print(list(itertools.product([1,2,3], [4,5,6])))
[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]
Cartesian product (with one iterable and itself):
>>> print(list(itertools.product([1,2], repeat=3)))
[(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2), (2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)]