如何从列表列表和另一个列表创建字典?

时间:2018-07-06 16:49:07

标签: python arrays list dictionary

我有这个数组:

[[330.0, 539.0, 241.0, 387.0],
 [544.0, 754.0, 243.0, 387.0],
 [1190.0, 1279.0, 241.0, 386.0],
 [545.0, 754.0, 393.0, 445.0],
 [1190.0, 1279.0, 99.0, 196.0],
 [544.0, 754.0, 98.0, 195.0],
 [330.0, 539.0, 393.0, 444.0],
 [760.0, 969.0, 143.0, 194.0],
 [760.0, 969.0, 242.0, 391.0],
 [329.0, 539.0, 100.0, 142.0],
 [759.0, 968.0, 492.0, 695.0],
 [975.0, 1185.0, 491.0, 642.0],
 [975.0, 1183.0, 242.0, 387.0],
 [1189.0, 1279.0, 491.0, 642.0],
 [975.0, 1184.0, 99.0, 141.0],
 [55.0, 307.0, 568.0, 626.0],
 [330.0, 527.0, 534.0, 576.0],
 [329.0, 539.0, 586.0, 642.0],
 [55.0, 228.0, 203.0, 240.0],
 [55.0, 227.0, 164.0, 200.0],
 [100.0, 308.0, 0.0, 106.0],
 [545.0, 754.0, 493.0, 549.0],
 [55.0, 274.0, 611.0, 639.0],
 [336.0, 527.0, 501.0, 543.0]]

还有一个:

[0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 3, 3, 1, 1, 1, 2, 0, 1, 3]

它们都是同一个尺寸,如何将它们合并成一个字典

{[330.0, 539.0, 241.0, 387.0]:0, [544.0, 754.0, 243.0, 387.0]:0 etc...}

1 个答案:

答案 0 :(得分:2)

列表不可散列,但是可以使用元组:

data1 = [[330.0, 539.0, 241.0, 387.0], [544.0, 754.0, 243.0, 387.0], [1190.0, 1279.0, 241.0, 386.0], [545.0, 754.0, 393.0, 445.0], [1190.0, 1279.0, 99.0, 196.0], [544.0, 754.0, 98.0, 195.0], [330.0, 539.0, 393.0, 444.0], [760.0, 969.0, 143.0, 194.0], [760.0, 969.0, 242.0, 391.0], [329.0, 539.0, 100.0, 142.0], [759.0, 968.0, 492.0, 695.0], [975.0, 1185.0, 491.0, 642.0], [975.0, 1183.0, 242.0, 387.0], [1189.0, 1279.0, 491.0, 642.0], [975.0, 1184.0, 99.0, 141.0], [55.0, 307.0, 568.0, 626.0], [330.0, 527.0, 534.0, 576.0], [329.0, 539.0, 586.0, 642.0], [55.0, 228.0, 203.0, 240.0], [55.0, 227.0, 164.0, 200.0], [100.0, 308.0, 0.0, 106.0], [545.0, 754.0, 493.0, 549.0], [55.0, 274.0, 611.0, 639.0], [336.0, 527.0, 501.0, 543.0]]
data2 = [0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 3, 3, 1, 1, 1, 2, 0, 1, 3]
final_result = {tuple(a):b for a, b in zip(data1, data2)}

输出:

{(330.0, 539.0, 241.0, 387.0): 0, (544.0, 754.0, 243.0, 387.0): 0, (1190.0, 1279.0, 241.0, 386.0): 0, (545.0, 754.0, 393.0, 445.0): 1, (1190.0, 1279.0, 99.0, 196.0): 0, (544.0, 754.0, 98.0, 195.0): 0, (330.0, 539.0, 393.0, 444.0): 1, (760.0, 969.0, 143.0, 194.0): 1, (760.0, 969.0, 242.0, 391.0): 0, (329.0, 539.0, 100.0, 142.0): 0, (759.0, 968.0, 492.0, 695.0): 0, (975.0, 1185.0, 491.0, 642.0): 0, (975.0, 1183.0, 242.0, 387.0): 0, (1189.0, 1279.0, 491.0, 642.0): 0, (975.0, 1184.0, 99.0, 141.0): 0, (55.0, 307.0, 568.0, 626.0): 3, (330.0, 527.0, 534.0, 576.0): 3, (329.0, 539.0, 586.0, 642.0): 1, (55.0, 228.0, 203.0, 240.0): 1, (55.0, 227.0, 164.0, 200.0): 1, (100.0, 308.0, 0.0, 106.0): 2, (545.0, 754.0, 493.0, 549.0): 0, (55.0, 274.0, 611.0, 639.0): 1, (336.0, 527.0, 501.0, 543.0): 3}