-1

python list comprehension, an example would be great.

  • 1
    its not quite clear what you want to do. does your shuffled list have to have city name followed by true/false or is it all shuffled completely? if you only care about new york and true specifically, why not just pick one of the neighbors of new york in the new list and replace it with one of the true values in that list? – Nullman May 12 '19 at 10:32
  • According to me your data structure is not reflecting the semantics of your data. You should use a list of "pairs" (for example tuples or lists if you want them to be modifiable). Then you can flatten it back if your interface requires the data format you provided. – Giuseppe Marra May 12 '19 at 10:41

2 Answers2

1

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)
tevemadar
  • 12,389
  • 3
  • 21
  • 49
0
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.

sonus21
  • 5,178
  • 2
  • 23
  • 48