Lista de ceros en python [duplicar]


Esta pregunta ya tiene una respuesta aquí:

¿Cómo puedo crear un list que contenga solo ceros? Quiero ser capaz de crear una ceros list para cada {[4] {} en[5]}

Por ejemplo, si el int en el rango era {[7] } obtendré:

[0,0,0,0]

Y para 7:

[0,0,0,0,0,0,0]
 179
Author: Michael Hoffman, 2011-12-16

8 answers

#add code here to figure out the number of 0's you need, naming the variable n.
listofzeros = [0] * n

Si prefiere ponerlo en la función, simplemente ingrese ese código y agregue return listofzeros

Que se vería así:

def zerolistmaker(n):
    listofzeros = [0] * n
    return listofzeros

Salida de muestra:

>>> zerolistmaker(4)
[0, 0, 0, 0]
>>> zerolistmaker(5)
[0, 0, 0, 0, 0]
>>> zerolistmaker(15)
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
>>> 
 301
Author: Tiffany,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-12-16 01:02:12
$python 2.7.8

from timeit import timeit
import numpy

timeit("list(0 for i in xrange(0, 100000))", number=1000)
> 8.173301935195923

timeit("[0 for i in xrange(0, 100000)]", number=1000)
> 4.881675958633423

timeit("[0] * 100000", number=1000)
> 0.6624710559844971

timeit('list(itertools.repeat(0, 100000))', 'import itertools', number=1000)
> 1.0820629596710205

Debe usar [0] * n para generar una lista con n ceros.

Vea por qué [] es más rápido que list()

Sin embargo, hay una gotcha, tanto itertools.repeat como [0] * n crearán listas cuyos elementos se refieren a la misma id. Esto no es un problema con objetos inmutables como enteros o cadenas, pero si intenta crear una lista de objetos mutables como una lista de listas ([[]] * n), entonces todos los elementos se referirán al mismo objeto.

a = [[]] * 10
a[0].append(1)
a
> [[1], [1], [1], [1], [1], [1], [1], [1], [1], [1]]

[0] * n creará la lista inmediatamente mientras repeat se puede utilizar para crear la lista perezosamente cuando se accede por primera vez.

Si está tratando con una gran cantidad de datos y su problema no necesita una longitud variable de la lista o varios tipos de datos dentro de la lista, es mejor usar matrices numpy.

timeit('numpy.zeros(100000, numpy.int)', 'import numpy', number=1000)
> 0.057849884033203125

numpy los arrays también consumirán menos memoria.

 40
Author: Seppo Erviälä,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:18:21

La forma más fácil de crear una lista donde todos los valores son iguales es multiplicar una lista de un elemento por n.

>>> [0] * 4
[0, 0, 0, 0]

Así que para tu bucle:

for i in range(10):
    print [0] * i
 23
Author: Andrew Clark,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-12-15 23:49:14
$ python3
>>> from itertools import repeat
>>> list(repeat(0, 7))
[0, 0, 0, 0, 0, 0, 0]
 7
Author: kev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-12-16 00:51:27
zlists = [[0] * i for i in range(10)]

zlists[0] es una lista de 0 ceros, zlists[1] es una lista de 1 a cero, zlists[2] es una lista de 2 ceros, etc.

 5
Author: kindall,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-12-15 23:50:52

zeros=[0]*4

Puede reemplazar 4 en el ejemplo anterior con el número que desee.

 3
Author: Lelouch Lamperouge,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-12-15 23:49:34

Si quieres una función que devuelva un número arbitrario de ceros en una lista, prueba esto:

def make_zeros(number):
    return [0] * number

list = make_zeros(10)

# list now contains: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
 2
Author: Gavin Anderegg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-12-15 23:57:41

Aquí está la forma xrange :

list(0 for i in xrange(0,5)) 
 1
Author: bugfree,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-12-16 00:14:53