Creating a list based on value stored in variable in python

前端 未结 2 1212
情歌与酒
情歌与酒 2020-12-22 08:09

I have a variable with a string value in it. I want to create a list with the value as its name/identifier, then append values to the list. So assuming variable s = \"

相关标签:
2条回答
  • 2020-12-22 08:23

    You can use globals():

    >>> strs = "temp1"
    >>> globals()[strs] = []
    >>> temp1
    []
    

    But using a dict for such purpose would be more appropriate:

    >>> dic = {strs:[]}
    >>> dic["temp1"]
    []
    
    0 讨论(0)
  • 2020-12-22 08:25

    Don't. Creating dynamic variables is rarely a good idea, and if you are trying to create local names (inside a function), difficult and greatly affects performance.

    Use a dictionary instead:

    lists = {}
    lists[strs] = []
    lists[strs].append(somevalue)
    

    Namespaces are just default dictionaries for code to look up names in. It is a lot easier and cleaner to create more such dictionaries.

    You can still access the global (module namespace with the globals() function, which returns a (writable) dictionary. You can access the function local namespace with locals(), but writing to this usually has no effect as local namespace access in functions has been optimized.

    In Python 2 you can remove that optimisation by using a exec statement in the function. In Python 3, you can no longer switch off the optimisation as the exec statement has been replaced by the exec() function, which means the compiler can no longer detect with certainty that you are potentially writing to the local namespace with it.

    0 讨论(0)
提交回复
热议问题