简体   繁体   中英

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

if I have a list, say:

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

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

var1 = xx
var2 = yy
var3 = zz

without knowing how long the list is, how would I do this? I have tried:

max = len(ll)
count = 0
for ii in ll:
    varcount = ii
    count += 1
    if count == max:
        break

I know that varcount is not a valid way to create a dynamic variable, but what I'm trying to do is create var0 , var1 , var2 , var3 etc based on what the count is.

Edit: :

Never mind, I should start a new question.

Generally speaking, it is not recommended 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, eg 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) )

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.

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.

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

Instead, do this:

>>> var = ['xx','yy','zz']
>>> var[0]
'xx'
>>> var[1]
'yy'
>>> var[2]
'zz'

I am assuming you are obtaining the list by way of an SQL query. Why can't you 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 lose the versatility you are working toward.

I have found a decent application for it. I have a bunch of csv files which I want to save as a dataframe under their name:

all_files = glob.glob(path + "/*.csv")
name_list = []
for f in all_files:
    name_list.append(f[9:-4])
for i,n in enumerate(name_list):
    globals()[n] = pd.read_csv(all_files[i])

This should do it (though using exec is not recommended):

for num in range(len(your_list)):
    exec('var'+str(num)+' = your_list[num]')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM