1
import random


def shuffle(L):

    random.shuffle(A)
    random.shuffle(B)

say my L is ["1", "2", "3", "4", "5", "6"]

I split the list into [1, 2, 3] and [4, 5, 6]

how do I combine the two lists, in a random order, but making sure the first number in the new list is either the first number from A or B

But making sure that each time I run the function, a new list is generated that still has either "1" or "4" as the first element

if u90
  • 105
  • 2
  • 9
  • 1
    `newA = list(A)`,`random.shuffle(newA[1:])` ? – NiziL Nov 06 '16 at 19:55
  • Apart from the 1st item in the new list being either 1 or 4 can the other items from `L` be in any order in the new list? – PM 2Ring Nov 06 '16 at 19:59
  • yes that's what I want, I want the first item in the new list to be 1 or 4, then the rest in any random order – if u90 Nov 06 '16 at 20:17
  • @Nizil what would that do? – if u90 Nov 06 '16 at 20:21
  • @ifu90 DSM exposed that `random.shuffle(newA[1:])` won't affect `newA`... So these line doesn't do what you want. I've certainly used too much Numpy's array in these past years. – NiziL Nov 07 '16 at 10:28

2 Answers2

0

You may do it using random.randint() and random.shuffle() as:

import random
l1, l2 = [1, 2, 3], [4, 5, 6]

random_num = random.randint(0, 1)  # will randomly return `0` or `1`

if random_num:
    first_elem, temp_list = l1[0], l1[1:]+l2
else:
    first_elem, temp_list = l2[0], l1+l2[1:]

random.shuffle(temp_list)  # randomly shuffles the list
new_list = [first_elem] + temp_list
# Value of "new_list":
# [4, 3, 2, 5, 6, 1]
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
0

Here is a generic answer for a list split in n parts:

from random import choice

def shuff(lst, n=2):
    size = len(lst) // n
    subs = (lst[i:i+size] for i in range(0, len(lst), size))
    return [choice(sub) for sub in zip(*subs)]

Then you can use this function like this:

lst = [1, 2, 3, 4, 5, 6]

print(shuff(lst, 2))
# [4, 2, 3]

print(shuff(lst, 3))
# [5, 6]
Delgan
  • 18,571
  • 11
  • 90
  • 141