我有三个条件:转移条件,真实条件和错误条件。
t_list
中的项目,并从p_list
或n_list
输出其他输入,但不正在转换的输入。 'OR'
,我要使用n_list
,否则-如果逻辑为'AND'
,我要使用p_list
。t_list = ['Input 1 transitions to true', 'Input 2 transitions to true', 'Input 3 transitions to true']
p_list = ['Input 1 is true', 'Input 2 is true', 'Input 3 is true']
n_list = ['Input 1 is false', 'Input 2 is false', 'Input 3 is false']
我正在定义一种为我的输出条件生成第4个列表的方法。
num_inputs = len(t_List)
logic = 'OR' #or 'AND' based on prior input
def combination_generator (t_List, p_List, n_List, logic, num_inputs):
count = 0
final_array = []
temp_array = []
for item in t_List:
temp_array.append(item)
if logic == 'OR':
for item in n_List:
temp_array.append(item)
elif logic == 'AND':
for item in p_List:
temp_array.append(item)
我最初的解决方案是使用itertools.combinations()
,如下所示:
for x in itertools.combinations(temp_array, num_inputs):
#file.write(f'{count} {x}\n')
count+=1
final_array.append(x)
我根据计数值手动选择了要添加到输出数组的输出组合。
我觉得似乎有一个更好的解决方案,也许是列表理解。
final_list = [item for item in n_List if logic == 'OR']
理想的输出:
'AND':
output_array = [['Input 1 transitions to true', 'Input 2 is true', 'Input 3 is true'],
['Input 1 is true', 'Input 2 transitions to true', 'Input 3 is true'],
['Input 1 is true', 'Input 2 is true', 'Input 3 transitions to true'],]
'OR':
output_array = [['Input 1 transitions to true', 'Input 2 is false', 'Input 3 is false'],
['Input 1 is false', 'Input 2 transitions to true', 'Input 3 is false'],
['Input 1 is false', 'Input 2 is false', 'Input 3 transitions to true'],]
答案 0 :(得分:0)
这应该可以正常工作:
def comb_gen(t_list, p_list, n_list, logic):
if logic == 'OR':
return [[p if j != i else s for j, p in enumerate(p_list)] for i, s in enumerate(t_list)]
if logic == 'AND':
return [[p if j != i else s for j, p in enumerate(n_list)] for i, s in enumerate(t_list)]
输出:
>>> t_list = ['Input 1 transitions to true', 'Input 2 transitions to true', 'Input 3 transitions to true']
>>> p_list = ['Input 1 is true', 'Input 2 is true', 'Input 3 is true']
>>> n_list = ['Input 1 is false', 'Input 2 is false', 'Input 3 is false']
>>> comb_gen(t_list, p_list, n_list, 'OR')
[['Input 1 transitions to true', 'Input 2 is true', 'Input 3 is true'],
['Input 1 is true', 'Input 2 transitions to true', 'Input 3 is true'],
['Input 1 is true', 'Input 2 is true', 'Input 3 transitions to true']]
>>> comb_gen(t_list, p_list, n_list, 'AND')
[['Input 1 transitions to true', 'Input 2 is false', 'Input 3 is false'],
['Input 1 is false', 'Input 2 transitions to true', 'Input 3 is false'],
['Input 1 is false', 'Input 2 is false', 'Input 3 transitions to true']]