繁体   English   中英

从子列表中随机选择以填充空子列表

[英]Random selection from a sub-list to fill an empty sub-list

我有两个列表列表,

A = [['a'],[],['l'],[]]
B = [['m','n'],['p'],[],['q','r','s']]

我需要输出是

c = [['a'],['p'],['l'],['s']]

每当 AI 中有一个空子列表时,想要从 B 的相应子列表中随机选择一个。

我的方法不起作用

import random

c = [x+random.sample(y,1) for x,y in zip(A,B) if len(x)==0 and len(y)>=1]

您可以使用条件表达式来决定要存储在列表中的元素:

from random import choice

[a if a else [choice(b)] for a, b in zip(A, B)]

您可以使用or运算符从B使用random.choices回退到随机选择:

from random import choices
[a or choices(b) for a, b in zip(A, B)]

您需要像这样使用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']]

暂无
暂无

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

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