Seite 1 von 1

slicen von mehrdimensionalen Listen

Verfasst: Mittwoch 10. März 2010, 11:45
von joh#
Hallo,

ich möchte jede Instanz (hat als Datenattribut eine mehrdim. Liste)
gerne ohne Seiteneffekte, also unabhängig:

Code: Alles auswählen

class KL(object):
    lx=[]
    def __init__(self):
        self.lx=[[1,3,1,4],
                 [1,9,2,8,3,7],
                 [4,4,7,4,7]]

    def data(self):
        return [self.lx[0],
                self.lx[1],
                self.lx[2]]

l1=KL()
l2=KL()

print 'l1:         ', l1.lx
l2.lx=l1.data()
l2.lx[0].sort()
l2.lx[1].sort()
l2.lx[2].sort()
print 'l2 sortiert:', l2.lx
print 'l1       ??:', l1.lx
es wird aber auch l1 mitsortiert (ist ja das gleiche Stück Speicher, nur
mit versch. Referenzen):
l1: [[1, 3, 1, 4], [1, 9, 2, 8, 3, 7], [4, 4, 7, 4, 7]]
l2 sortiert: [[1, 1, 3, 4], [1, 2, 3, 7, 8, 9], [4, 4, 4, 7, 7]]
l1 ??: [[1, 1, 3, 4], [1, 2, 3, 7, 8, 9], [4, 4, 4, 7, 7]]
>>>
bei eindimensionalen Listen funktioniert l2=l1[:] aber hier?
Gruß
joh

Verfasst: Mittwoch 10. März 2010, 11:57
von cofi
http://docs.python.org/library/copy.html#copy.deepcopy

Du machst in `data` btw nichts anderes als `return self.lx[:]`. Ohne `copy.deepcopy` und mit Slicing:

Code: Alles auswählen

 def data(self):
    return [self.lx[0][:],
            self.lx[1][:],
            self.lx[2][:]]

Auch sollte man `l` in Code vermeiden. Gleiches gilt fuer das Klassenattribut `lx`.

Verfasst: Mittwoch 10. März 2010, 16:48
von joh#
besten Dank!
joh