利用Python进行数据分析

列表、集合和字典的推导式

2018-12-28  本文已影响3人  庵下桃花仙

1、列表推导式:允许过滤一个容器的元素,用简明的表达式转换 传递给过滤器的元素,并生成一个新列表。

[expr for val in collection if condition]

In [1]: strings = ['a', 'as', 'bat', 'car', 'dove', 'python']

In [2]: [x.upper() for x in strings if len(x) > 2]
Out[2]: ['BAT', 'CAR', 'DOVE', 'PYTHON']

2、字典推导式

dict_comp = {key-expr : value-expr for value in collection if condition}

3、集合推导式

set_comp = {expr for val in collection if condition}

In [3]: unique_lengths = {len(x) for x in strings}

In [4]: unique_lengths
Out[4]: {1, 2, 3, 4, 6}

In [5]: set(map(len, strings))
Out[5]: {1, 2, 3, 4, 6}
In [6]: loc_mapping = {val : index for index, val in enumerate(strings)}

In [7]: loc_mapping
Out[7]: {'a': 0, 'as': 1, 'bat': 2, 'car': 3, 'dove': 4, 'python': 5}

4、嵌套列表推导式

获得一个列表,包含2个以上字母e的名字。
for 循环

In [10]: name_of_interest = []

In [13]: for names in all_data:
    ...:     enough_es = [name for name in names if name.count('e') >= 2]
    ...:     name_of_interest.extend(enough_es)
    ...:

In [14]: name_of_interest
Out[14]: ['Steven']

嵌套列表推导式

In [15]: result = [name for names in all_data for name in names if name.count('e') >= 2]

In [16]: result
Out[16]: ['Steven']

列表推导式的for循环部分是根据嵌套顺序排列的,所有的过滤条件依然放在尾部。

In [17]: some_tuples = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]

In [18]: flattened = [x for tup in some_tuples for x in tup]

In [19]: flattened
Out[19]: [1, 2, 3, 4, 5, 6, 7, 8, 9]

嵌套推导式的语法要和列表推导式中的列表推导式区分开。列表推导式中的列表推导式也很有用。

In [20]: [[x for x in tup] for tup in some_tuples]
Out[20]: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
上一篇下一篇

猜你喜欢

热点阅读