简体   繁体   中英

Shuffle function for list in a list

Trying to append two lists and shuffle elements of both lists simultaneously with one enumerate function

I am using two functions:

  1. Appending list_b to list_a
  2. Shuffling list_a and giving using enumerate function to do indexing.

In addition, I also want to shuffle elements of list_b within the new shuffled list_a and use same enumerate function to index items of both lists in a same number sequence. Below is where I stand so far.

list_a = ["alpha", "beta", "romeo", "nano", "charlie"]
list_b = [1,2,3,4,5,6,7]
from random import shuffle
list_a.append(list_b)
shuffle(list_a)
print(list_a)

for idx, val in enumerate(list_a, start=1):
    print(idx, val)

Output

['nano', 'charlie', 'alpha', 'beta', [1, 2, 3, 4, 5, 6, 7], 'romeo']

1 nano
2 charlie
3 alpha
4 beta
5 [1, 2, 3, 4, 5, 6, 7]
6 romeo

I may be missing something, but you can just shuffle list_b before appending it to list_a :

from random import shuffle

list_a = ["alpha", "beta", "romeo", "nano", "charlie"]
list_b = [1, 2, 3, 4, 5, 6, 7]

shuffle(list_b)

list_a.append(list_b)
shuffle(list_a)
print(list_a)

for idx, val in enumerate(list_a, start=1):
    print(idx, val)

Outputs

['alpha', 'charlie', 'nano', [1, 4, 5, 2, 7, 3, 6], 'beta', 'romeo']
1 alpha
2 charlie
3 nano
4 [1, 4, 5, 2, 7, 3, 6]
5 beta
6 romeo

Try this:

# append
from random import sample, shuffle
list_a.append(list_b)

# shuffle the list within the list
for i, v in enumerate(list_a): 
     if isinstance(v, list):
          list_a[i] = sample(v, len(v))

# shuffle the list
list_a = sample(list_a, len(list_a))

# unpack elements
list_c = []
for e in list_a:
    if not isinstance(e, list):
        list_c.append(e)
        continue
    for v in e: 
        list_c.append(v)

# print
for i, v in enumerate(list_c): 
    print(i, v)

You can easily get your result by basic concept if-else AND type method. I have added 2 lines in your code:-

list_a = ["alpha","beta","romeo","nano","charlie"]
list_b = [1,2,3,4,5,6,7]
from random import shuffle
list_a.append(list_b)
shuffle(list_a)
print(list_a)
print()

for idx, val in enumerate(list_a, start=1):
    if type(val) is list:   # This is newly added.
        shuffle(val)
        print(idx, val)
    else:   
        print(idx, val)

I hope it may help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM