How to use function for each items of multiple array

Question:

I have array such as [['C'],['F','D'],['B']]

Now I want to use functino for each items in multiple array.

The result I want is like this [[myfunc('C')],[myfunc('F'),myfunc('D')],[myfunc('B')]]

At first I tried like this. However, it did not give me the output I was expecting:

[myfunc(k) for k in [i for i in chordsFromGetSet]]

What is the best solution for this goal?

Asked By: whitebear

||

Answers:

You were close. You need to call myfunc() in the nested list comprehension, not in the outer list comprehension.

[[myfunc(k) for k in sublist] for sublist in chordsFromGetSet]
Answered By: Barmar

What you have is actually pretty close. What your current list comprehension is doing is iterating over your outer list and returning each item and then calling myfunc on each of those lists. To, call myfunc on each element in each inner list, do this:

[myfunc(k) for i in chordsFromGetSet for k in i]

Of course, this won’t preserve the structure of your object. To do that, you need to create a new list from the output of myfunc for each list in your list-of-lists:

[[myfunc(k) for k in i] for i in chordsFromGetSet]
Answered By: Woody1193
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.