How to assign each element of a list to a separate variable?

前端 未结 7 1704
花落未央
花落未央 2020-12-01 14:12

if I have a list, say:

ll = [\'xx\',\'yy\',\'zz\']

and I want to assign each element of this list to a separate variable:

v         


        
相关标签:
7条回答
  • 2020-12-01 14:31

    I am assuming you are obtaining the list by way of an SQL query - why you can't commit to a length. With that it seems obvious to me that you wish to take those values and execute additional SQL commands using each value from that newly acquired list separately. This is not a way off concept if you take it from an SQL perspective, and if I am correct I will provide the syntax. However you will not need to create separate variable names with this solution and not loose the versatility you are working toward. IF I AM WRONG SORRY FOR WASTING YOUR TIME

    0 讨论(0)
  • 2020-12-01 14:37

    Not a good idea to do this; what will you do with the variables after you define them?

    But supposing you have a good reason, here's how to do it in python:

    for n, val in enumerate(ll):
        globals()["var%d"%n] = val
    
    print var2  # etc.
    

    Here, globals() is the local namespace presented as a dictionary. Numbering starts at zero, like the array indexes, but you can tell enumerate() to start from 1 instead.

    But again: It's unlikely that this is actually useful to you.

    0 讨论(0)
  • 2020-12-01 14:40

    You should go back and rethink why you "need" dynamic variables. Chances are, you can create the same functionality with looping through the list, or slicing it into chunks.

    0 讨论(0)
  • 2020-12-01 14:43

    generally speaking it is not suggested to use that kind of programming for a large number of list elements / variables.

    However the following statement works fine and as expected

    a,b,c = [1,2,3]
    

    This is called "destructuring".

    it could save you some lines of code in some cases, e.g. I have a,b,c as integers and want their string values as sa,sb,sc:

    sa, sb,sc = [str(e) for e in [a,b,c]]
    

    or, even better

    sa, sb,sc = map(str, (a,b,c) )
    
    0 讨论(0)
  • 2020-12-01 14:44

    If the number of Items doesn't change you can convert the list to a string and split it to variables.

    wedges = ["Panther", "Ali", 0, 360]
    a,b,c,d = str(wedges).split()
    print a,b,c,d
    
    0 讨论(0)
  • 2020-12-01 14:47

    Instead, do this:

    >>> var = ['xx','yy','zz']
    >>> var[0]
    'xx'
    >>> var[1]
    'yy'
    >>> var[2]
    'zz'
    
    0 讨论(0)
提交回复
热议问题