python列表解析,也叫列表表达式
发布时间:2020-02-24 11:53:36
作者:ynkulusi
列表解析是python迭代机制的一种应用,它常用于实现创建新的列表,因此要放置于[]中
[expression for iter_var in iterable]
[expression for iter_var in iterable if cond_expr]
列表解析总共有两种形式:
1. [i for i in range(k) if condition]:此时if起条件判断作用,满足条件的,将被返回成为最终生成的列表的一员。
2. [i if condition else exp for exp]:此时if...else被用来赋值,满足条件的i以及else被用来生成最终的列表。
以上情况对多个for仍然成立。
示例
print([i for i in range(10) if i%2 == 0])
print([i if i == 0 else 100 for i in range(10)])
[0, 2, 4, 6, 8]
[0, 100, 100, 100, 100, 100, 100, 100, 100, 100]
In [77]: l1 = [1,2,3,4,5]
In [78]: l2 = []
In [79]: for i in l1:
....: l2.append(i**2)
....:
In [80]: print l2
[1, 4, 9, 16, 25]
In [81]: l3 = [ i**2 for i in l1 ]
In [82]: print l3
[1, 4, 9, 16, 25]
In [83]: l4 = [ i**2 for i in l1 if i>=3 ]
In [84]: print l4
[9, 16, 25]
In [19]: l1 = [[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12]]
In [20]: [[row[i] for row in l1] for i in range(4)]
Out[20]: [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
In [22]: zip(*l1)
Out[22]: [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
In [68]: for x in range(1,11):
...: print '{0:1d} {1:2d} {2:5d}'.format(x, x*x, x*x*x)
...:
...:
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
In [18]: a={'one':[1,2,3], 'two':['A','B','C']}
In [19]: s=[{i: a[i][j] for i in a} for j in range(len(a.values()[1]))]
In [20]: s
Out[20]: [{'one': 1, 'two': 'A'}, {'one': 2, 'two': 'B'}, {'one': 3, 'two': 'C'}]
In [185]: d1={'a':[1,2,3,4], 'b':[5,6,7,8]}
In [186]: l1=[{k: d1[k][i] for k in d1} for i in range(len(d1.values()[0]))]
In [187]: l1
Out[187]: [{'a': 1, 'b': 5}, {'a': 2, 'b': 6}, {'a': 3, 'b': 7}, {'a': 4, 'b': 8}]
In [47]: s=[[a[i][j] for i in a] for j in range(len(a.values()[0]))]
In [48]: s
Out[48]: [['A', 1], ['B', 2], ['C', 3]]
In [235]: a=[1, 2, 3, 4, 5]
In [236]: b=['a', 'b', 'c', 'd', 'e']
In [237]: l1=[]
In [238]: l1.append(a)
Out[238]: l1.append(b)
In [239]: l1
Out[239]: [[1, 2, 3, 4, 5], ['a', 'b', 'c', 'd', 'e']].
In [240]: [[row[i] for row in l1] for i in range(5)]
Out[240]: [[1, 'a'], [2, 'b'], [3, 'c'], [4, 'd'], [5, 'e']]
In [246]: [{row[i] for row in l1} for i in range(5)]
Out[246]: [{1, 'a'}, {2, 'b'}, {3, 'c'}, {4, 'd'}, {5, 'e'}]
分类:python
评论数:1
阅读数:1192