pythonlist嵌套
⑴ list可以嵌套嗎 python
可以
>>> a=[]
>>> a.append(a)
>>> a
[[...]]
⑵ python 嵌套list讀取
b1=[[2]*3]*2
b2=[[2,2,2],[2,2,2]]
這個兩個定義的變數其實時不一樣的
b2一個list,包含兩個list元素
b1是1個list元素的兩個淺拷貝,可以理解成兩個指向[2]*3的指針。
出現這種問題,實際上理解的誤區,[2]*3
=
[2,2,2]
就想當然的把[[2]*3]*2=
[2,2,2]*2
=
[[2,2,2]
[2,2,2]]
其實[[]]是一個list的淺拷貝(或者理解成指向list指針)
更詳細的可以看下python的文檔,裡面有說明。
⑶ 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 嵌套list
defiseven(l):
foriinl:
ifi%2:
returnFalse
returnTrue
defonly_evens(ll):
r=[]
foriinll:
ifiseven(i):
r.append(i)
returnr
printonly_evens([[1,2,4],[4,0,6],[22,4,3],[2]])
Python 2.7 執行結果
[[4, 0, 6], [2]]
其中 iseven 函數判斷 list 是不是都是偶數
⑸ Python中嵌套list使用append的問題
你這樣寫代碼會把腦袋繞暈
請舉一個有點實際意義的例子(用有意義的變數名)
⑹ 關於Python列表嵌套問題
這個叫元組的拆包或解包。
list1迭代返回的是元組,那麼for循環內就是
m,n = ('c',1)
m,n = ('Python',2)
...
⑺ python列表的嵌套該怎麼理解
不對…
這里
[row[i] for row in matrix] for i in range(4)
是一個整體,不然row[i] for row in matrix里的i是哪來的…
這個List Comprehension相當於一個嵌套循環,外層循環變數是i,內層循環變數是row。
把列表的外層循環改為普通for循環的話,等價於:
temp_list = []
for i in range(4):
temp_list.append([row[i] for row in matrix])
把列表的兩層循環都改為普通for循環寫法,大致相當於:
temp_list = []
for i in range(4):
temp_list.append([])
for row in matrix:
temp_list[-1].append(row[i])
⑻ python 將兩個list合並成為一個嵌套的list
除了直接相加(生成新的list),還有兩種方法(修改其中一個list):
用list的extend方法,L1.extend(L2),該方法將參數L2的全部元素添加到L1的尾部,例如:
1
2
3
4
5
>>> L1 = [1, 2, 3, 4, 5]
>>> L2 = [20, 30, 40]
>>> L1.extend(L2)
>>> L1
[1, 2, 3, 4, 5, 20, 30, 40]
用切片(slice)操作,L1[len(L1):len(L1)] = L2和上面的方法等價,例如:
1
2
3
4
5
6
>>> L1 = [1, 2, 3, 4, 5]
>>> L2 = [20, 30, 40]
>>> L1[len(L1):len(L1)] = L2
>>>
>>> L1
[1, 2, 3, 4, 5, 20, 30, 40]
但切片方法用起來更靈活,可以插入到頭部,或其他任意部位,例如:
加到開頭:
1
2
3
4
5
>>> L1 = [1, 2, 3, 4, 5]
>>> L2 = [20, 30, 40]
>>> L1[0:0] = L2
>>> L1
[20, 30, 40, 1, 2, 3, 4, 5]
加到中間:
1
2
3
4
5
6
>>> L1 = [1, 2, 3, 4, 5]
>>> L2 = [20, 30, 40]
>>>
>>> L1[1:1] = L2
>>> L1
[1, 20, 30, 40, 2, 3, 4, 5]
參考
1.《python libarary referece》5.6.4. Mutable Sequence Types:
(oschina文檔鏡像地址)http://tool.oschina.net/uploads/apidocs/python2.7.3/library/stdtypes.html#mutable-sequence-types
⑼ 請教python列表嵌套問題
可以這樣寫:
l=[{'name':'張三','性別':'男','年齡':12,'成績':60},{'name':'張三','性別':'女','年齡':12,'成績':80},{'name':'李四','性別':'男','年齡':13,'成績':75},{'name':'王五','性別':'男','年齡':12,'成績':20}]
l=list(filter(lambda d:d['name']=='張三',l))
print(l)
這是運行截圖:
⑽ 如何使用Python3實現嵌套List中的元素兩兩相乘
一、
AList=[[5,8],[3,6],[4,5],[3,8],[6,2]]
foriinrange(len(AList)):
AList.append(AList[0][0]*AList[0][1])
temp=AList.pop(0)
print("AList="+str(AList))
二、
AList=[[5,8],[3,6],[4,5],[3,8],[6,2]]
foriinAList:
AList_Fist.append(i[0])
print("AList_Fist="+str(AList_Fist))