我正在尝试从字典列表中获取所有值,以便它应该涵盖所有可能的不同组合。例如
list = [{'a': 32}, {'b': 2541}, {'c': 530}, {'d': 55}, {'a': 544}, {'b': 44}, {'c': 54}, {'d': 454}, {'a': 42}, {'b': 655}, {'c': 459}, {'d': 665}, {'a': 2145}, {'b': 450}, {'c': 342}, {'d': 186}, ........]
我想一次选择两对,如下所示
image1 = img[2541:55, 32:530]
image2 = img[44:454, 544:54]
我也想用所有其他可能的组合来做到这一点
image1 = img[2541:55, 32:530]
image2 = img[655:665, 42:459]
像这样我可以做12个不同的对如何自动执行此操作以获得所需的值?
此代码将获取您的列表数据并创建一个存储您的img[b:d, a:c]
的列表:
where_you_start = 0
where_you_stop = 12
image = [img[0:0, 0:0] for i in range(where_you_start, where_you_stop)] # Initialize list
for i in range(where_you_start, where_you_stop):
img_data = {}
for elem in list[i * 4:i * 4 + 4]:
for key, value in elem.items():
img_data[key] = value
image[i] = img[img_data['b']:img_data['d'], img_data['a']:img_data['c']]
set1 = (image[1], image[2])
set2 = (image[1], image[3])
...
setn = (image[x], image[y])
where_you_start
是您要开始从list
中的数据创建img
的位置。
where_you_stop
是你想停下来的地方。
代码循环访问定义的范围,并采用列表中的四个值: list[i * 4:i * 4 + 4]
只负责获取四个值。
要访问不同的集合,请在image
列表中选择不同的项目
如果你想要所有可能的组合,你可以使用 itertools.product
.
第一步是重新排列 'a', 'b', 'c' and 'd'
的所有可能值。假设您的列表每 4 个步骤重复一次,为了清楚起见,您可以放入字典,如下所示:
l1 = {k: [e.get(k) for e in your_list][i::4] for i, k in enumerate(['a', 'b', 'c', 'd'])}
l1
>>
{'a': [32, 544, 42, 2145],
'b': [2541, 44, 655, 450],
'c': [530, 54, 459, 342],
'd': [55, 454, 665, 186]}
然后:
from itertools import product
combinations = [c for c in product(*l1.values())]
combinations
>>[(32, 2541, 530, 55),
(32, 2541, 530, 454),
(32, 2541, 530, 665),
(32, 2541, 530, 186)
....
(2145, 450, 342, 186)] #256 combinations in this case (4**4)