如何根据宽度和高度生成x和y值?

问题描述 投票:0回答:1

我需要根据宽度和高度生成一个xy值。在这里,我有一个像这样的字典列表,

myInput = [{"height":3,"value":5},{"height":5,"value":1} and so on..]

我正在对该命令进行迭代以生成x和y值。基于宽度,我要生成x,基于高度,我要生成y。我没有在代码中使用宽度。 width的用途是计算x值。在这里,宽度为4,因此x的最大值为4。我不知道如何在代码中制作它。帮助我提供一些解决方案。

这是示例代码,

width = 4
myInput = [{"height":3,"value":5},{"height":5,"value":1}]
temp_d = {}
result = []
for i in myInput:
    print(i["height"])
    for j in range(i["height"]):
        temp_d["x"] = j
        temp_d["y"] = j
        temp_d["value"] = i["value"]
        result.append(temp_d)
        temp_d={}
print(result)

我的输出:

[{'x': 0, 'y': 0, 'value': 5}, 
{'x': 1, 'y': 1, 'value': 5}, 
{'x': 2, 'y': 2, 'value': 5}, 
{'x': 0, 'y': 0, 'value': 1}, 
{'x': 1, 'y': 1, 'value': 1}, 
{'x': 2, 'y': 2, 'value': 1}, 
{'x': 3, 'y': 3, 'value': 1}, 
{'x': 4, 'y': 4, 'value': 1}]

必需的输出:

[
{'x': 0, 'y': 0, 'value': 5}, {'x': 0, 'y': 1, 'value': 5}, 
{'x': 0, 'y': 2, 'value': 5}, {'x': 0, 'y': 3, 'value': 5},
{'x': 1, 'y': 0, 'value': 5}, {'x': 1, 'y': 1, 'value': 5}, 
{'x': 1, 'y': 2, 'value': 5}, {'x': 1, 'y': 3, 'value': 5},
{'x': 2, 'y': 0, 'value': 5}, {'x': 2, 'y': 1, 'value': 5}, 
{'x': 2, 'y': 2, 'value': 5}, {'x': 2, 'y': 3, 'value': 5},
{'x': 3, 'y': 0, 'value': 5}, {'x': 3, 'y': 1, 'value': 5}, 
{'x': 3, 'y': 2, 'value': 5}, {'x': 3, 'y': 3, 'value': 5},
{'x': 4, 'y': 0, 'value': 5}, {'x': 4, 'y': 1, 'value': 5}, 
{'x': 4, 'y': 2, 'value': 5}, {'x': 4, 'y': 3, 'value': 5},

{'x': 0, 'y': 4, 'value': 1}, {'x': 0, 'y': 5, 'value': 1}, 
{'x': 1, 'y': 4, 'value': 1}, {'x': 1, 'y': 5, 'value': 1},
{'x': 2, 'y': 4, 'value': 1}, {'x': 2, 'y': 5, 'value': 1}, 
{'x': 3, 'y': 4, 'value': 1}, {'x': 3, 'y': 5, 'value': 1},
{'x': 4, 'y': 4, 'value': 1}, {'x': 4, 'y': 5, 'value': 1},

]
python python-3.x list python-2.7 dictionary
1个回答
0
投票

两个输入的输出看起来都不同:{“ height”:3,“ value”:5},{“ height”:5,“ value”:1}

对于{“ height”:3,“ value”:5},看起来结果是在对宽度和高度进行迭代之后计算得出的

要实现这一点,您可以尝试以下操作:

import itertools
for i in myInput:
    for p,q in itertools.product(range(width+1),range(i["height"]+1)):
        temp_d["x"] = p
        temp_d["y"] = q
        temp_d["value"] = i["value"]
        result.append(temp_d)
        temp_d={}
print(result)

但是{“ height”:5,“ value”:1}的输出与{“ height”:3,“ value”:5}的输出不同,上述逻辑将生成不同的输出。您能否详细说明这个问题,以便我们可以适当地修改逻辑?


0
投票
def my_func():
    width = 4
    myInput = [{"height":3,"value":5},{"height":5,"value":1}]
    temp_d = {}
    result = []
    curr = 0
    for i in myInput:
        print(i["height"])
        for k in range(width+1):
            for j in range(curr,i["height"]+1):
                temp_d["x"] = k
                temp_d["y"] = j
                temp_d["value"] = i["value"]
                result.append(temp_d)
                temp_d={}
        curr = i["height"] + 1
    print(result
© www.soinside.com 2019 - 2024. All rights reserved.