Here is a mock-example of what I'm trying to achieve:
I have initially a list of empty lists of size 5:
l = [[] for _ in range(5)]
Then, in a for loop that does 4 iterations, I have function that returns a list of indexes. I'd like to append "t" to the lists with those indexes.
Something like:
for t in range(4):
idx = function_that_gives_indexes()
l[idx].append(t)
Let's say that function_that_gives_indexes()
, gives for each loop these value: [1], [2, 4], [] and [0, 1]
. I'd like l
to be:
l = [[3], [0, 3], [1], [], [1]]
What's the most pythonic way of doing this?
Since your function returns a list each time then your corrected code snippet is something like
for t in range(4):
for idx in function_that_gives_indexes():
l[idx].append(t)
And it does not look promising to try to make it more pythonic.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.