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
448 views
in Technique[技术] by (71.8m points)

python - Change value of currently iterated element in list

problem: when you use construction

for a in _list_:
    print a

it prints every item in array. But you can't alter array. Is it possible to alter value of array (something like a=123, but that ain't working) I know it's possible (for example in while loop), but I want to do it this way (more elegant)

In PHP it would be like

foreach ($array as &$value) {
    $value = 123;
}

(because of & sign, is passed as reference)

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)
for idx, a in enumerate(foo):
    foo[idx] = a + 42

Note though, that if you're doing this, you probably should look into list comprehensions (or map), unless you really want to mutate in place (just don't insert or remove items from iterated-on list).

The same loop written as a list comprehension looks like:

foo = [a + 42 for a in foo]

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

...