['New York', 'TRUE', 'Thimphu', 'FALSE', 'Tokyo', 'FALSE', 'Japan', 'FALSE', 'India', 'FALSE']

This is my list, I want to generate new list from it but a new list should have TRUE and New York move together whenever a new list is generated, index doesn't matter but 'New York', 'TRUE', should be adjacent to one another.for eg: following can be a new list:

[ 'Thimphu', 'FALSE', 'New York', 'TRUE','Tokyo', 'FALSE', 'Japan', 'FALSE', 'India', 'FALSE']
[ 'Thimphu', 'FALSE','Tokyo', 'FALSE', 'Japan', 'FALSE', 'India', 'FALSE' 'New York', 'TRUE',]

2 Answers

1
tevemadar On Best Solutions

Let's start copy-pasting along the idea that the list should be divided into pairs or a "list of lists", the result shuffled, and flattened back:

1) your post

data = ['New York', 'TRUE', 'Thimphu', 'FALSE', 'Tokyo', 'FALSE', 'Japan', 'FALSE', 'India', 'FALSE']

2) Split a python list into other "sublists" i.e smaller lists

chunks = [data[x:x+2] for x in range(0, len(data), 2)]

3) shuffle is in random

import random
random.shuffle(chunks)

4) How to make a flat list out of list of lists

flat_list = [item for sublist in chunks for item in sublist]

Combined together:

data = ['New York', 'TRUE', 'Thimphu', 'FALSE', 'Tokyo', 'FALSE', 'Japan', 'FALSE', 'India', 'FALSE']
chunks = [data[x:x+2] for x in range(0, len(data), 2)]
import random
random.shuffle(chunks)
flat_list = [item for sublist in chunks for item in sublist]
print(flat_list)
0
sonus21 On
import random
size = 2
country_list = ['New York', 'TRUE', 'Thimphu', 'FALSE', 'Tokyo', 'FALSE', 'Japan', 'FALSE', 'India', 'FALSE']
country_dict = {}
for i in range(0, len(country_list), 2):
    country_dict[country_list[i]] = country_list[i + 1]
random_sample = random.sample(country_dict.items(), size)
final_list = [item for l in random_sample for item in l]
print(final_list)

Conver list to dictionary then use random method on dictionary items and later flat that to the list.

In this random.sample has been used which can sample the input the given size <= input size.

We can also use random.shuffle which will randomize the dict items.