I have a dataclass foo
which has a member item_li: list[item]
, item is a dataclass which has a member sub_item_li: list[sub_item]
I want to return list[sub_item]
from a method of foo
. I am primarily looking for a solution with list comprehension.
I got it already working with the following list comprehension which I split into 2 lines:
sub_item_li_li: list[list[sub_item]] = [sub_item_li for sub_item_li in [item.sub_item_li for item in self.item_li]] all_sub_item_li: list[sub_item] = [sub_item for sublist in sub_item_li_li for sub_item in sublist] return all_sub_item_li
Is there a way to achieve that without having to create a list of lists first?
Advertisement
Answer
Oli answered the question:
return [sub_item for item in self.item_li for sub_item in item.sub_item_li]