Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

python - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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, 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) )

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...