嵌套列表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)
這是運行截圖: