0

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?

Woody1193
  • 7,252
  • 5
  • 40
  • 90
whitebear
  • 11,200
  • 24
  • 114
  • 237

2 Answers2

2

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]
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

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]
Woody1193
  • 7,252
  • 5
  • 40
  • 90