-1

What I want to do is to cuts the list in two parts, as evenly sized as possible, then interleaves the elements of the two parts to form the shuffled list. For example, there is a list

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

and I want to rearrange it into

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

I want to change the list in this way. But I have no idea about how to insert all elements into right position.

Jayyyyyy
  • 197
  • 1
  • 10
  • 3
    The algorithm you describe doesn't involve any randomness. Do you actually want to use random.shuffle or do you want to implement what you've said with the cutting and interleaving? – Corentin Pane Nov 06 '19 at 10:40
  • I think it is just cutting and interleaving. – Jayyyyyy Nov 06 '19 at 10:48

3 Answers3

1
li, res = [1,2,3,4,5,6,7,8], []
length = len(li)
half = length//2
for i, j in zip(li[:half], li[half:]):
    res.append(i)
    res.append(j)
if length % 2 != 0:
    res.append(li[length - 1])
Prem Ib
  • 136
  • 2
  • 11
0
from itertools import chain
my_list = [1, 2, 3, 4, 5, 6, 7, 8]
print(list(chain(*zip(my_list[:len(my_list)//2], my_list[len(my_list)//2:]))) + ([] if len(my_list) % 2 == 0 else [my_list[-1]]))

You didn't specify what you expect if the list has an odd number of items, so I assumed you want to append the remaining item at the end of the final list.

Corentin Pane
  • 4,794
  • 1
  • 12
  • 29
0

Here's a simpler one:

from math import ceil
my_list = [1,2,3,4,5,6]

result = sum([my_list[i::ceil(len(my_list)/2)] for i in range(ceil(len(my_list)/2))],[])

# [1, 4, 2, 5, 3, 6]

my_list = [1,2,3,4,5,6,7]

result = sum([my_list[i::ceil(len(my_list)/2)] for i in range(ceil(len(my_list)/2))],[])

# [1, 5, 2, 6, 3, 7, 4]
Sayandip Dutta
  • 15,602
  • 4
  • 23
  • 52