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

python - How to generate new list from variable in a loop?

My actual example is more involved so I boiled the concept down to a simple example:

l = [1,2,3,4,5,6,7,8]

for number in l:
    calc = number*10
    print calc

For each iteration of my loop, I end up with a variable (calc) I'd like to use to populate a new list. My actual process involves much more than multiplying the value by 10, so I'd like to be able to set each value in the new list by this method. The new code might look like this:

l = [1,2,3,4,5,6,7,8]

for number in l:
    calc = number*10
    # set calc as x'th entry in a new list called l2 (x = iteration cycle)

print l2

Then it would print the new list: [10,20,30,40,...]

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

There are several options...

List comprehensions

Use list comprehension, if short enough:

new_list = [number * 10 for number in old_list]

map()

You could also use map(), if the function exists before (or you will eg. use lambda):

def my_func(value):
    return value * 10

new_list = map(my_func, old_list)

Be aware, that in Python 3.x map() does not return a list (so you would need to do something like this: new_list = list(map(my_func, old_list))).

Filling other list using simple for ... in loop

Alternatively you could use simple loop - it is still valid and Pythonic:

new_list = []

for item in old_list:
    new_list.append(item * 10)

Generators

Sometimes, if you have a lot of processing (as you said you have), you want to perform it lazily, when requested, or just the result may be too big, you may wish to use generators. Generators remember the way to generate next element and forget whatever happened before (I am simplifying), so you can iterate through them once (but you can also explicitly create eg. list that stores all the results).

In your case, if this is only for printing, you could use this:

def process_list(old_list):
    for item in old_list:
        new_item = ...  # lots of processing - item into new_item
        yield new_item

And then print it:

for new_item in process_list(old_list):
    print(new_item)

More on generators you can find in Python's wiki: http://wiki.python.org/moin/Generators

Accessing "iteration number"

But if your question is more about how to retrieve the number of iteration, take a look at enumerate():

for index, item in enumerate(old_list):
    print('Item at index %r is %r' % (index, item))

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

...