Print a new vector by changing the order of the elements of the original vector

Asked

Viewed 46 times

0

How do I change the order of the elements of a vector v1 printing a new vector v2 with these changes?

You can write a function def?

Example:

v1 = [2,51,68,10]
v2 = [10,2,51,68]

2 answers

0


Every vector loads: Index and Value

v1 = [2,51,68,10]

print(v[0]) #2
print(v[1]) #51
print(v[2]) #68
print(v[3]) #10

As apparently you want to change the position without obeying any logic (i.e from higher to lower) you will need to manually change the index when creating the second vector:

v1 = [2,51,68,10]
print(v1) #[2, 51, 68, 10]

v2=[v1[1],v1[0],v1[3],v1[2]] #Trocas feitas manualmente
print(v2) #[51, 2, 10, 68]

There may be smarter solutions, but I couldn’t see any pattern in the exchange of indexes or values themselves.

0

You can use the Random package sample:

from random import sample
v1 = [2,51,68,10]

def embaralha(x):
    return sample(v1, len(v1))

v2 = embaralha(v1)
print(v2)

One of the possible exits:

[51, 68, 10, 2]

Browser other questions tagged

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