我有以下表格中的列表l
。我需要从此列表中随机生成k
(在此示例中为六个)列表中的数量,以便一次只从子列表中选择一个元素。
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
我可以写一个for循环,并在遇到列表时选择一个随机元素。但我正在寻找更优雅的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")
答案 0 :(得分:1)
要使用的关键函数是来自choice
模块的random
,它从任何具有已知大小的可迭代对象中随机选择一个值。所有这些对象都有__getitem__
方法和__len__
方法(这两个方法都需要应用choice
函数),因此可以使用内置函数hasattr
检查是否可以应用choice
。解决方案变得简单明了:
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])
答案 1 :(得分:0)
您可以重复此过程6次。它会随机重新排序您的内部列表并获取第一个值。
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])
答案 2 :(得分:0)
你也可以尝试这个:
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)
可能的输出:
[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]