我有两个列表,
A = [['a'],[],['l'],[]]
B = [['m','n'],['p'],[],['q','r','s']]
我需要输出为
c = [['a'],['p'],['l'],['s']]
只要A中有一个空子列表,我都要从B的相应子列表中追加一个随机选择。
我的方法不起作用
import random
c = [x+random.sample(y,1) for x,y in zip(A,B) if len(x)==0 and len(y)>=1]
答案 0 :(得分:3)
您可以使用conditional expression来确定要在列表中存储的元素:
from random import choice
[a if a else [choice(b)] for a, b in zip(A, B)]
答案 1 :(得分:2)
您可以使用or
使用B
运算符退回到random.choices
的随机选择项:
from random import choices
[a or choices(b) for a, b in zip(A, B)]
答案 2 :(得分:1)
您需要像这样使用if
:
import random
A = [['a'],[],['l'],[]]
B = [['m','n'],['p'],[],['q','r','s']]
C = [
a_sub_list if a_sub_list else [random.choice(b_sub_list)] for a_sub_list, b_sub_list in zip(A,B)
]
print(C)
>>> [['a'], ['p'], ['l'], ['q']]