質問

This is a conceptual problem, I need to instantiate a number of 'nodes' for a network simulation. The naming is the problem - I need a method to autogenerate names for the instances (any method that allows me to track and reference the nodes after creation will do)

to give a better idea of what I need, here's what most of the loop would look like with hashtags shoehorned into where the problem is. x and y will be defined in the parent function.

    for n in range(1000):
        #n, but somehow converted into the name of the dict# = {
            'address':n,
            'resistance':x,
            'special':[],
            'parent':y,
            'children':[],
            'adjnodes':[]
    }

Apologies for being a noob. I've searched high and low for the answer to this so if it's obvious then I'm misusing the lingo or something; in that case please let me know what lingo to use and I'll grab my hat and be on my way. Not being sarcastic, just prefer to be taught harshly when necessary. Thanks.

役に立ちましたか?

解決

It sounds like you're trying to create these as a bunch of separate variables, and then store the name of the variable in the address field of each one.

Don't do that. See Keep data out of your variable names and Why you don't want to dynamically create variables for an explanation as to why. But the short version is that trying to do so is the only reason you're having a problem in the first place.

Why not just create a single list of all of the nodes? Then your address can just be an index into that list. For example:

nodes = []
for n in range(1000):
    nodes.append({
        'address':n,
        'resistance':x,
        'special':[],
        'parent':y,
        'children':[],
        'adjnodes':[]
    })

Or, if you plan to be adding and removing nodes as you go along, so list indices won't stay consistent, just use a dict:

nodes = {}
for n in range(1000):
    nodes[n] = {
        'address':n,
        'resistance':x,
        'special':[],
        'parent':y,
        'children':[],
        'adjnodes':[]
    }

他のヒント

If n is meaningful, you can put each of those dicts into another dict with n as the key.

If n is not meaningful, just add those dicts to a list.

Either way, keep your data out of your variable names.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top