Hi. I'm trying to do something that's kinda easy for me to do in c++ but not in python :P
I want to create a list with lists.
for example
LIST:
list item 1: 0, 0, 0
list item 2: 5, 4, 3
list item 3: 0, 0, 0
That's actually what i', trying to do with the piece of code down here.
But for some reasom it wont work.
When I print the entire list I get the output:
5, 4, 3
5, 4, 3
5, 4, 3
code:
[code]
class data1:
list1 = [0] * 3
class data2:
list2 = []
def save(Class):
for i in xrange(0, 3):
Class.list2.append(data1())
"""Main"""
myClass = data2()
save(myClass)
# Adding some random numbers to one list
myClass.list2[1].list1[0] = 5
myClass.list2[1].list1[1] = 4
myClass.list2[1].list1[2] = 3
print myClass.list2
for i in xrange(0, 3):
print myClass.list2[i].list1[0] , ", " , myClass.list2[i].list1[1] , ", " , myClass.list2[i].list1[2]
[/code]
I'm obviously doing something wrong.
Can you please take a look and help me? ^^
I believe i can help you but i don't understand what you're trying to do. Do you want to have one list with 3 elements that are all lists?
I don't know why the hell you're doing it with classes, to put it bluntly (rudely?)
Notes: xrange is largely pointless
To get the output you want, do this
[code]
l = [[0, 0, 0], [5, 4, 3], [0, 0, 0]
[/code]
Also, one massive python gotcha is that if you do
[code]
l1 = [0, 0, 0]
l2 = [l1, l1, l1]
//or
l1 = [0, 1]
l2 = []
l2.append(l1)
l2.append(l1)
[/code]
You are not adding copies l1: you are adding references, so changing any of the elements in l1 will affect all the corresponding elements. I hope that makes sense.
well that's right Tommy. I'm working on an exporter for blender so there will be alot of lists with vertices, triangles and texture coords
so I want to classes to structure everything.
I found this way to do it in a md2 exporter script.
There is no point having a class that has a list as it's sole member: it is basically an irritating way to get at a list. Why not just use a list? I think you have the mindset of a C++ programmer, which will not serve you well when using python.
I'm a python 3 user so listen to TheBoff. You only need classes if you need multiple instances with the same methods but different attributes or something along those lines. Also really pay attention to the way variables only refer to lists and don't actually contain them. That culprit slowed my first project down by a week when i was starting out.
[QUOTE=TheBoff;22413861]I think you have the mindset of a C++ programmer, which will not server you well when using python.[/QUOTE]
I think you're so right :P
Ok i'll try to restructure my code and see what I can do.
Thanks for the help and tips
Sorry, you need to Log In to post a reply to this thread.