[英]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:我正在使用两个功能:
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.此外,我还想在新的 shuffled list_a 中对 list_b 的元素进行洗牌,并使用相同的 enumerate 函数以相同的编号顺序对两个列表的项目进行索引。 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
:我可能遗漏了一些东西,但是您可以在将list_b
附加到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.您可以通过基本概念if-else
AND type
方法轻松获得结果。 I have added 2 lines in your code:-我在您的代码中添加了 2 行:-
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.我希望它可以帮助你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.