当前位置: 动力学知识库 > 问答 > 编程问答 >

Assign different operators during python loop

问题描述:

I would like to assign loop results to a contineous operator, for instance:

for x in xrange(1, 5):

answer = 5 + x

How can I replace this with:

for x in xrange(1, 5):

answerx = 5 + x

Meaning, assigning the answers to answer1, answer2, etc.

Is this possible and how?

网友答案:

Your best bet is to use a list:

answers = []
for x in xrange(1, 5):
    answers.append(5 + x)

Then you can access the answers as answers[0] and so on.

...but a list comprehension is even nicer, as in Martijn Pieters' answer.

网友答案:

Append answers to a list, or better still, use a list comprehension:

answers = [5 + x for x in xrange(1, 5)]

Now you can address answers[0], answers[1], etc.

You can also make it a dictionary:

answers = {'answer{}'.format(x): 5 + x for x in xrange(1, 5)}

Whenever you feel the urge to generate variable names from data, you are probably looking to use a dictionary or list instead. Keep data out of your variable names.

网友答案:

From first comments, giving complete example :

answer = []
for x in xrange(1,5) :
  answer.append(5 + x)

and as said list comprehension is more Python-way of doing this

answer = [5+x for x in xrange(1,5)]

网友答案:

I don't think you would want to do that, but here's a solution (try this on ipython):

for x in xrange(1, 5):
    locals()["answer"+str(x)] = 5 + x
网友答案:

The solution to your question is:

for x in xrange(1,5):
   exec("answer"+str(x)+"= 5 + x")

like this, you can use answer1, answer2... as individual variables. Some people might say that is is not a "good practise", but I use this statement from time to time an find it very useful for certain applications...

分享给朋友:
您可能感兴趣的文章:
随机阅读: