Domanda

I need a random list of integers without 0. I'm using random.sample(xrange(y),z) but I don't want 0 in this list. Thank you

È stato utile?

Soluzione

Start your range at 1 then:

random.sample(xrange(1, y), z)

That's all there is to it, really.

Demo:

>>> list(xrange(3))
[0, 1, 2]
>>> list(xrange(1, 3))
[1, 2]

xrange() doesn't just produce a series of integers up to an endpoint, it can also produce a series between two points; a third option gives you a step size:

>>> list(xrange(1, 6, 2))
[1, 3, 5]

Altri suggerimenti

Simple, just specify another argument:

random.sample(xrange(1, y), z)
                     ^

Notice the 1. This is the start argument, meaning that 0 is not included here.

Example:

>>> list(xrange(1, 10))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top