简体   繁体   中英

Generating a List with A sublists and B elements in each sublist

for some reason

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

is not the same as:

list=[[0,0,0], [0,0,0], [0,0,0], [0,0,0]]

although they print the same, but they don't work the same way... Can someone clarify if there is a difference between the lists, and which is it?

In the first example, you're appending the same sublist four times to list (which is an unfortunate name because it also shadows the built-in name, but that's not pertinent to the problem here). So if you modify one of the sublists, you modify all of them.

In the second example, you create a list with four identical but distinct sublists.

At any rate, that code looks more like a C program than a Python script - you should read a Python tutorial to start learning the language as it's meant to be used.

The correct way to create an a * b -sized "matrix" with entries predefined to 0 is:

>>> a = 4
>>> b = 3
>>> matrix = [[0] * b for _ in range(a)]
>>> matrix
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]

they are working same if youo simple print the id of each sublists

print map(id, list) #will print the id of all sublist
sublists[1] = 2
print sublists, list, 

output:-

[0, 0, 0]
[3053888556L, 3053888556L, 3053888556L, 3053888556L]
[0, 2, 0] [[0, 2, 0], [0, 2, 0], [0, 2, 0], [0, 2, 0]]
>>> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM