Automatically create vector in Python

Asked

Viewed 6,824 times

3

I’m new to Python and need help with the following:

  • I have a variable (x) that takes an integer value.
  • I want this variable to be used to create a vector with 1 row and (x) columns.
  • This vector must have random values and integers from 0 to 100.

Example:

To x = 4

My way out should be:

[50,40,60,70]

2 answers

4


You can use the module Random to generate random values:

If you do not want repeated values:

import random

x = 5
saida = []
for _ in range(x):
    saida.append(random.choice(range(100)))
print saida # [5, 75, 9, 38, 33]

Or better yet:

import random

x = 5
saida = random.sample(range(100),  x)
print(saida) # [69, 47, 43, 64, 16]

If there can be repeated values:

import random

x = 5
saida = []
for _ in range(x):
    saida.append(random.randint(0, 100))
print saida # [74, 12, 15, 32, 74]

Note that you can use a list comprehension for any of the above solutions:

import random

x = 5
saida = [random.randint(0, 100) for _ in range(x)]
print saida # [88, 37, 17, 27, 58]

DEMONSTRATION of the three above

  • I vaccinated and you went faster :p Good answer +1

  • Thank you very much! It worked perfectly!

  • You’re welcome @Danilo

3

It’s simple. It would be nice to take a look at module random, there are several ways to work with random numbers.

randint returns an integer between the two that have been passed by parameter.

from random import randint

x = int(raw_input('entre com o valor desejado: '))
vec = []

for i in range (x):
    vec.append(randint(0, 100))

print(vec)

See working on repl.it.

  • Thank you very much! It helped me a lot.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.