How to iterate over elements in a list and each element is entered into a function

Possible duplicate:
Python: for each list item, a function in the list is applied

for example, let's say I have an array or list

myList = [a,b,c,d] 

and I have a function that generates a random number.

How do I go through a list and each of them an element in this list receives a random number generated by a function and be added to the element?

So, let's say that "a" is the first in the list, "a" goes into a function in which a random number is generated (say 5) and added to "a", the result should be "[a + 5, b + .. .....].

+4
source share
4 answers

You use the understanding:

 [func(elem) for elem in lst] 

In your specific example, you can use an expression that sums up the values:

 [elem + func() for elem in myList] 

where func() returns your random number.

+4
source

Use the map() function, which applies the function to each iteration element and returns a list of results:

 def myfunc(x): return x ** 2 >>> map(func, [1,2,3]) [1, 4, 9] 
+1
source

I assume that you are talking about integers. This little script should do what you want:

 import random def gen_rand(number): generated = random.randint(1, 10) # you can specify whatever range you want print generated return number + generated myList = [1,2,3,4,5] print str(myList) myList = [gen_rand(item) for item in myList] print str(myList) 

Or you can use the map function instead of the for loop. Replace

 myList = [gen_rand(item) for item in myList] 

with

 myList = map(gen_rand,myList) 
0
source

If you need one liner :-)

 myList = [1,2,3,4] [ i + map(lambda i: random.randint(10,20), myList)[index] for index, i in enumerate(myList) ] 
0
source

Source: https://habr.com/ru/post/1438838/


All Articles