简体   繁体   English

从可能包含子列表的元素列表中生成k个随机列表

[英]Generate k random list from a list of elements possibly containing sublist

I have a list l in the following form. 我有以下形式的清单l I need to randomly generate k (six in this example) number of lists from this list so that only one element is selected from the sublists at a time. 我需要从该列表中随机生成k (在此示例中为6个)列表,以便一次仅从子列表中选择一个元素。

l = [1,2,3,[11,22,33,44], 4,5,6, [22,33,44], 5, [99,88]]

Result: 

1,2,3, 22, 4,5,6, 22 ,5, 88
1,2,3, 33, 4,5,6, 44 ,5, 88
1,2,3, 44, 4,5,6, 22 ,5, 99
1,2,3, 22, 4,5,6, 33 ,5, 99
1,2,3, 33, 4,5,6, 33 ,5, 99
1,2,3, 33, 4,5,6, 44 ,5, 88

I can write a for loop and pick a random element whenever I encountered a list. 每当遇到列表时,我都可以编写for循环并选择一个随机元素。 But i am looking for more elegant pythonic way to do this. 但是我正在寻找更优雅的pythonic方式来做到这一点。

l = [1,2,3,[11,22,33,44], 4,5,6, [22,33,44], 5, [99,88]]
k = 0
for k in range(6):
    new_l = []
    for i in range(len(l)):
        if isinstance(l[i], list):
            new_l.append(np.random.choice(l[i]))
        else:
            new_l.append(l[i])
    print(new_l)
    print("\n")

The key function to use is choice from the random module, which randomly selects a value from any iterable object with a known size. 要使用的关键功能是从random模块中进行choice ,该模块从具有已知大小的任何可迭代对象中随机选择一个值。 All such objects have a __getitem__ method as well as a __len__ method (both of which are needed to apply the choice function), so the builtin function hasattr can be used to check whether choice can be applied or not. 所有这些对象都具有__getitem__方法和__len__方法(都需要应用choice功能),因此内置函数hasattr可用于检查是否可以应用choice The solution becomes straightforward: 解决方案变得简单明了:

from random import choice

l = [1,2,3,[11,22,33,44], 4,5,6, [22,33,44], 5, [99,88]]

for n in range(6):
    print([choice(item) if hasattr(item,'__getitem__') else item for item in l])

You can repeat this procedure 6 times. 您可以重复此过程6次。 It randomly reorders your inner lists and takes the first value. 它随机地重新排列您的内部列表并采用第一个值。

l = [1,2,3,[11,22,33,44], 4,5,6, [22,33,44], 5, [99,88]]

for i in range(6):
    print([np.random.permutation(i)[0] if type(i) == list 
           else np.random.permutation([i])[0] 
           for i in l])

You can try this one too: 您也可以尝试以下方法:

import random

l = [1,2,3,[11,22,33,44], 4,5,6, [22,33,44], 5, [99,88]]

res = [random.choice(l[i]) if type(l[i]) is list else l[i] for i in range(len(l))]

print(res)

Possible outputs: 可能的输出:

[1, 2, 3, 44, 4, 5, 6, 22, 5, 99]
[1, 2, 3, 11, 4, 5, 6, 22, 5, 99]
[1, 2, 3, 22, 4, 5, 6, 33, 5, 88]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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