Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > fr.comp.lang.python > #3028

Re: remplir un tableau

From Benoit Izac <use.reply.to@INVALID.ADDRESS>
Newsgroups fr.comp.lang.python
Subject Re: remplir un tableau
Date 2018-01-30 07:19 +0100
Message-ID <87efm7vpge.fsf@izac.org> (permalink)
References <5a6fa2b6$0$7180$426a74cc@news.free.fr>

Show all headers | View raw


Bonjour,

Le 29/01/2018 à 23:39, Fabrice a écrit dans le message
<5a6fa2b6$0$7180$426a74cc@news.free.fr> :

> je voulais remplir un tableau avec des nombres aléatoires mais j'ai 50
> fois la même ligne !
>
> j'ai fait :
>
> import matplotlib.pyplot as plt
> import random
>
> image = [[0]*50]*50

Le problème est là. Tu crées une liste contenant 50 fois une référence
vers la même liste qui contient 50 zéros :

>>> image = [[0]*50]*50
>>> id(image[0])
140001800012424
>>> id(image[1])
140001800012424

Alors qu'en faisant comme cela :

>>> image = [[0]*50 for _ in range(50)]
>>> id(image[0])
140001800012936
>>> id(image[1])
140001800012744

-- 
Benoit Izac

Back to fr.comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar


Thread

remplir un tableau Fabrice <professeur.leclercq@gmail.com> - 2018-01-29 23:39 +0100
  Re: remplir un tableau Benoit Izac <use.reply.to@INVALID.ADDRESS> - 2018-01-30 07:19 +0100
    Re: remplir un tableau Fabrice <professeur.leclercq@gmail.com> - 2018-01-31 16:15 +0100
      Re: remplir un tableau Benoit Izac <use.reply.to@INVALID.ADDRESS> - 2018-01-31 18:50 +0100
  Re: remplir un tableau Nicolas <nicolasp@aaton.com> - 2018-01-30 09:53 +0100
    Re: remplir un tableau Fabrice <professeur.leclercq@gmail.com> - 2018-01-31 16:17 +0100
  Re: remplir un tableau marc.marc@marc.org - 2018-01-31 09:25 +0100
    Re: remplir un tableau Fabrice <professeur.leclercq@gmail.com> - 2018-01-31 16:23 +0100

csiph-web