Return the elements of a randomized list

Asked

Viewed 32 times

2

I have an array generated by a string.split(), and the value of this string is obtained by a input.

That is to say:

string = input("Digite os Nomes separados por Vírgula")
arrTeste = string.split(",")

The number of elements in the array is undefined, since the user can enter 5 names, 10 names... etc

It is possible to return all array elements randomly?

Example (Assuming the user has entered the three names below in input):

arrTeste = ["Junior", "Gabriel", "Henrique"]

The desired output would be something like:

print(funcaoAleatorizar)  ## suposição da função

@Gabriel, @Junior, @Henrique  ## output do terminal

I still have the detail I need to work out @ before the elements generated, but I do this myself.

1 answer

4


It is possible to return all array elements randomly?

Yes, just use the function shuffle module random:

from random import shuffle

arrTeste = ["Junior", "Gabriel", "Henrique"]
shuffle(arrTeste)

print(', '.join('@' + nome for nome in arrTeste))

With this the list elements are "shuffled" randomly.

Then just print the names with the @ in front and separated by a comma as desired.


Remembering that shuffle changes the list in-place.

But if you want to keep the original list intact, an alternative is to use sample:

from random import sample

arrTeste = ["Junior", "Gabriel", "Henrique"]
embaralhado = sample(arrTeste, len(arrTeste))
print(', '.join('@' + nome for nome in embaralhado))
print(arrTeste) # lista original permanece intacta

sample generates a sample of the list, ensuring that there are no repeated elements. But as in the second parameter I passed the size of the list, then at the end it will generate a sample of the list size (and as it ensures that there is no repetition, the result will have all the elements of the list in random order). And the original list will remain intact.

  • Our friend! It’s much simpler than I expected, how amazing! Thank you! Enlightening and didactic.

Browser other questions tagged

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