我有两个具有不可比元素的有序列表:
l1 = [1, 2, 3, 4]
l2 = [obj1, obj2, obj3]
我想将它们随机合并到一个列表中,但要保持它们的相对顺序,如下所示:
ml = [1, 2, obj1, obj2, 3, obj3, 4]
或
ml = [obj1, 1, 2, 3, obj2, obj3, 4]
如果有人帮助我,我将不胜感激。
答案 0 :(得分:3)
import random
l1 = [1, 2, 3, 4]
l2 = ["obj1", "obj2", "obj3"]
def merge_random(lists):
res = []
while lists:
li = random.choice(lists)
res.append(li.pop(0))
lists = [li for li in lists if li]
return res
print(merge_random((l1, l2)))
示例输出:
['obj1', 'obj2', 1, 2, 'obj3', 3, 4]
Jon Clements建议使用此解决方案。它使用generator,并且不会修改用户输入。显然,这是解决该问题的更Python方式。
import random
def f(*iterables):
todo = [iter(it) for it in iterables]
while todo:
idx = random.randrange(len(todo))
try:
yield next(todo[idx])
except StopIteration:
del todo[idx]
可以这样使用:
l1 = [1, 2, 3, 4]
l2 = ["obj1", "obj2", "obj3"]
for i in f(l1, l2):
print(i)
示例输出:
obj1
1
2
obj2
obj3
3
4