开发者

Pythonic Referenced For Loop [duplicate]

开发者 https://www.devze.com 2023-03-31 14:52 出处:网络
This question already has answers here: Python Referenced For Loop (3 answers) Closed 9 years ago. I have a for loop as follows:
This question already has answers here: Python Referenced For Loop (3 answers) Closed 9 years ago.

I have a for loop as follows:

a=[1,2,3,4,5]
for i in a:
    i=6

What I would like is for every element of a to become 6.

Now I know that this for loop won't do it, because I am merely changing the what i refers to.

I instead could write:

a=[1,2,3开发者_Go百科,4,5]
for i in len(range(a)):
    a[i]=6

But that doesn't seem very Pythonic. What are good ways of doing this sort of thing? Obviously, setting everything to 6 is contrived example and, in reality, I would be doing more complicated (and wonderful) things. Therefore, answers should be generalised.


The for-variable is always a simple value, not a reference; there is no way to know that it came from a list and thus write back to the list on changing.

The len(a) approach is the usual idiom, although you need range (or xrange) too:

for i in range(len(a)):

or, just as commonly, use the enumerate function to get indexes as well as values:

for i, v in enumerate(a):
    a[i]= v+1

a list comprehension might be a good alternative, eg:

a= [6 for v in a]


This would probably be a good use for map() depending on what you're doing in real life. For example:

a = map(lambda x: 6, a)


You could use:

>>> a = [1, 2, 3, 4, 5]
>>> a = [6] * len(a)
>>> a
[6, 6, 6, 6, 6]
0

精彩评论

暂无评论...
验证码 换一张
取 消