Connect string value to a corresponding variable name

杀马特。学长 韩版系。学妹 提交于 2020-01-06 05:08:05

问题


This question has somehow to do with an earlier post from me. See here overlap-of-nested-lists-creates-unwanted-gap

I think that I have found a solution but i can't figure out how to implement it.

First the relevant code since I think it is easier to explain my problem that way. I have prepared a fiddle to show the code:

PYFiddle here

Each iteration fills a nested list in ag depending on the axis. The next iteration is supposed to fill the next nested list in ag but depending on the length of the list filled before.

The generell idea to realise this is as follows:

First I would assign each nested list within the top for-loop to a variable like that:

    x = ag[0]
    y = ag[1]
    z = ag[2] 

In order to identify that first list I need to access data_j like that. I think the access would work that way.

data_j[i-1]['axis']  

data_j[i-1]['axis'] returns either x,y or z as string

Now I need to get the length of the list which corresponds to the axis returned from data_j[i-1]['axis'].

The problem is how do I connect the "value" of data_j[i-1]['axis'] with its corresponding x = ag[0], y = ag[1] or z = ag[2]

Since eval() and globals() are bad practice I would need a push into the right direction. I couldn't find a solution

EDIT: I think I figured out a way. Instead of taking the detour of using the actual axis name I will try to use the iterator i of the parent loop (See the fiddle) since it increases for each element from data_j it kinda creates an id which I think I can use to create a method to use it for the index of the nest to address the correct list.


回答1:


I managed to solve it using the iterator i. See the fiddle from my original post in order to comprehend what I did with the following piece of code:

if i < 0:
    cond = 0
else:
    cond = i
pred_axis = data_j[cond]['axis']      

if pred_axis == 'x':
    g = 0
elif pred_axis == 'y':
    g = 1
elif pred_axis == 'z':
    g = 2   

calc_size = len(ag[g])
n_offset = calc_size+offset

I haven't figured yet why cond must be i and not i-1 but it works. As soon as I figure out the logic behind it I will post it.

EDIT: It doesn't work for i it works for i-1. My indices for the relevant list start at 1. ag[0] is reserved for a constant which can be added if necessary for further calculations. So since the relevant indices are moved up by the value of 1 from the beginning already i don't need to decrease the iterator in each run.



来源:https://stackoverflow.com/questions/48651440/connect-string-value-to-a-corresponding-variable-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!