[英]How to produce combinations from a list of tuples?
tuples
list
:params = ['sn', 'tp', 'v1', 'temp', 'slew']
list_tuple = [('Serial Number', [12345]),
('Test Points', ['TestpointA', 'TestpointC']),
('Voltage_1', [3.0, 3.3, 3.6, 0.0]),
('Temperature Setpoint', [0, 60]),
('Slew_1', [200, 400, 800, 1600, 3200, 6400])]
def what_i_want(test_tuple, params):
for sn in test_tuple[0][1]:
for tp in test_tuple[1][1]:
for v in test_tuple[2][1]:
for temp in test_tuple[3][1]:
for slew in test_tuple[4][1]:
print(f'{params[0]}: ', sn)
print(f'{params[1]}: ', tp)
print(f'{params[2]}: ', v)
print(f'{params[3]}: ', temp)
print(f'{params[4]}: ', slew)
print('\n')
what_i_want(list_tuple, params)
產生所需的輸出:
sn: 12345
tp: TestpointA
v1: 3.0
temp: 0
slew: 200
sn: 12345
tp: TestpointA
v1: 3.0
temp: 0
slew: 400
...
...
params
的長度對應於list_tuple
組的數量,這個長度可以變化。 元組中每個列表的長度也可以變化(即帶有序列號的列表可以是 3 或 4 個元素,而不是 1 個)。
我想使用遞歸來解包list_tuple
並按索引正確調用params
,這樣我就不必創建帶有一堆嵌套循環的類。 但是,這是我第一次使用遞歸,我只能產生以下結果:
def poo_doo(list_tuple):
for i in list_tuple:
if isinstance(i, tuple):
print(i[0])
poo_doo(i[1])
else:
print(i)
print('\n')
poo_doo(list_tuple)
產量:
Serial Number
12345
Test Points
TestpointA
TestpointC
Voltage_1
3.0
3.3
...
請提供幫助以使用最有效的方法產生所需的輸出,最好不要嵌套循環。
鏈接到完整類以提供更廣泛的理解: auto_filter 類
您可以使用itertools.product
:
import itertools
data = [('Serial Number', [12345]), ('Test Points', ['TestpointA', 'TestpointC']), ('Voltage_1', [3.0, 3.3, 3.6, 0.0]), ('Temperature Setpoint', [0, 60]), ('Slew_1', [200, 400, 800, 1600, 3200, 6400])]
params = ['sn', 'tp', 'v1', 'temp', 'slew']
for i in itertools.product(*[b for _, b in data]):
print('\n'.join(f'{a}:{b}' for a, b in zip(params, i)))
print('-'*20)
輸出(前三個結果):
sn:12345
tp:TestpointA
v1:3.0
temp:0
slew:200
--------------------
sn:12345
tp:TestpointA
v1:3.0
temp:0
slew:400
--------------------
sn:12345
tp:TestpointA
v1:3.0
temp:0
slew:800
--------------------
...
雖然itertools.product
是(也許)最干凈的解決方案,但可以使用帶有生成器的簡單遞歸函數:
def combination(d, current = []):
if len(current) == len(data):
yield current
else:
for i, a in enumerate(d):
for c in a:
yield from combination(d[i+1:], current = current+[c])
for i in combination([b for _, b in data]):
print('\n'.join(f'{a}:{b}' for a, b in zip(params, i)))
print('-'*20)
輸出(前三個結果):
sn:12345
tp:TestpointA
v1:3.0
temp:0
slew:200
--------------------
sn:12345
tp:TestpointA
v1:3.0
temp:0
slew:400
--------------------
sn:12345
tp:TestpointA
v1:3.0
temp:0
slew:800
--------------------
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.