-2

Basically, I want to make an algorithm that apply a function to each element in my list.

database = ['A', 'B', 'A', 'B', 'C']

And I have a function named Weighting.

def weighting(speed, time):
    return (speed * time)

I want to apply this function to each element of the array so,

mylist[0] = speed * time
mylist[1] = speed * time
mylist[2] = speed * time

etc..

And for each element, they have different speeds and time.

Then, I want to display the new array where each elements have been calculated based on the function weighting.

So far i did:

def weight(speed, time):
    return_list = []

    for x in return_list:
        x = speed * time
        return return_list
def run():
    database = ['A', 'B', 'A', 'B', 'C']

I am new to python, so could someone help me?

  • 1
    Please provide a [MCVE](https://stackoverflow.com/help/mcve) - your code is "vague". For example `weighting = speed * time` is not a function, and it is completely unclear how the elements of `database` are even relevant and supposed to be used. – timgeb Jan 13 '18 at 19:43

1 Answers1

0

For this you can use the built-in function called map. This function takes in two parameters which are a function and an iterable.

The function will apply the function to every item in the iterable and gives back the results.

With the code you have you could try something like this:

results = map(weight, database)

This will simply apply your function weight to the list database!

I hope this answer helped you and if you have any further question please feel free to post a comment below!

Micheal O'Dwyer
  • 1,193
  • 1
  • 13
  • 25
  • Thank you for your informative reply! But how to I assign different value of speed and time to each element of the list? for example I want the distance and speed to be 4 and 24 respectively for database[0] and 2 and 10 respectively for databse[1] etc.. Because I see that the map function applies the function written to all the elements in the list. If you get what I mean – Jason Chong Jan 13 '18 at 19:47
  • I think that to use this functionality with the `map` function may be too difficult for a beginner but here is a [SO post answering what you want to do](https://stackoverflow.com/questions/10834960/how-to-do-multiple-arguments-to-map-function-where-one-remains-the-same-in-pytho). For now you could just iterate through the database and pass the specific arguments that you want. – Micheal O'Dwyer Jan 13 '18 at 20:03