[英]Applying functions/methods within each sublist, not to the list of sublists as a whole in python
[英]Generating a List with A sublists and B elements in each sublist
由於某些原因
a=4
b=3
sublists=[]
p=0
while p<b:
sublists.append(0)
p+=1
list=[]
p=0
while p<a:
list.append(sublists)
p+=1
與以下內容不同:
list=[[0,0,0], [0,0,0], [0,0,0], [0,0,0]]
盡管它們打印的相同,但是它們的工作方式不同...有人可以弄清楚列表之間是否有區別,這是什么?
在第一個示例中,您要向list
追加四次相同的子list
(這是一個不幸的名稱,因為它也隱藏了內置名稱,但這與此處的問題無關)。 因此,如果您修改其中一個子列表,那么您將全部修改。
在第二個示例中,您將創建一個包含四個相同但不同的子列表的列表。
無論如何,該代碼看起來更像是C程序,而不是Python腳本-您應該閱讀Python教程以開始學習所要使用的語言。
創建預定義為0
的a
* b
大小的“矩陣”的正確方法是:
>>> a = 4
>>> b = 3
>>> matrix = [[0] * b for _ in range(a)]
>>> matrix
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
如果您簡單地打印每個子列表的id
,則它們的工作原理相同
print map(id, list) #will print the id of all sublist
sublists[1] = 2
print sublists, list,
輸出: -
[0, 0, 0]
[3053888556L, 3053888556L, 3053888556L, 3053888556L]
[0, 2, 0] [[0, 2, 0], [0, 2, 0], [0, 2, 0], [0, 2, 0]]
>>>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.