嵌套列表python
❶ python 嵌套的列表推导式怎么理解的呢
5.1.4. 嵌套的列表推导式
列表解析中的第一个表达式可以是任何表达式,包括列表解析。
考虑下面有三个长度为 4 的列表组成的 3x4 矩阵:
>>> matrix = [
... [1, 2, 3, 4],
... [5, 6, 7, 8],
... [9, 10, 11, 12],
... ]
现在,如果你想交换行和列,可以用嵌套的列表推导式:
>>> [[row[i] for row in matrix] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
像前面看到的,嵌套的列表推导式是对 for 后面的内容进行求值,所以上例就等价于:
>>> transposed = []
>>> for i in range(4):
... transposed.append([row[i] for row in matrix])
...
>>> transposed
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
反过来说,如下也是一样的:
>>> transposed = []
>>> for i in range(4):
... # the following 3 lines implement the nested listcomp
... transposed_row = []
... for row in matrix:
... transposed_row.append(row[i])
... transposed.append(transposed_row)
...
>>> transposed
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
在实际中,你应该更喜欢使用内置函数组成复杂流程语句。对此种情况 zip() 函数将会做的更好:
>>> list(zip(*matrix))
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
❷ Python怎么拉平嵌套列表
Python如何拉平(flatten)嵌套列表(nested
list)
有时候会用到嵌套的列表(list),比如
[1,
2,
[3,
4,
[5,
6]],
["abc",
"def"]]
如果将嵌套的列表拉平(flatten)呢?变成:
[1,
2,
3,
4,
5,
6,
"abc",
"def"]
方法有很多,目前了解到的各方面都比较好,也很pythonic的方法是:
def
flatten(l):
for
el
in
l:
if
hasattr(el,
"__iter__")
and
not
isinstance(el,
basestring):
for
sub
in
flatten(el):
yield
sub
else:
yield
el
l
=
[1,
2,
[3,
4,
[5,
6]],
["abc",
"def"]]
l2
=
[x
for
x
in
flatten(l)]
print
l2
#[1,
2,
3,
4,
5,
6,
"abc",
"def"]
❸ 请教python列表嵌套问题
可以这样写:
l=[{'name':'张三','性别':'男','年龄':12,'成绩':60},{'name':'张三','性别':'女','年龄':12,'成绩':80},{'name':'李四','性别':'男','年龄':13,'成绩':75},{'name':'王五','性别':'男','年龄':12,'成绩':20}]
l=list(filter(lambda d:d['name']=='张三',l))
print(l)
这是运行截图: