[Tutor] Break element into list while iterating
Peter Otten
__peter__ at web.de
Tue Jan 11 06:11:11 EST 2022
On 25/12/2021 18:11, Julius Hamilton wrote:
> Hey,
>
> I would like to do some kind of list comprehension where elements meeting
> certain conditions get split on a delimiter. They don’t become lists nested
> in one element in the previous list; the new elements just get inserted
> where the old one was.
>
> Like this:
>
> [“apple”, “pear”]
>
> ->
>
> [“a”, “p”, “p”, “l”, “e”, “pear”]
>
> Is there a list comprehension syntax where if I split an element with
> e.split(), I can “insert” those elements at the element they came from?
While you can solve this with a list comprehension...
>>> [y for x in ["apple", "pear"] for y in (x if x == "apple" else [x])]
['a', 'p', 'p', 'l', 'e', 'pear']
I recommend a generator instead:
>>> def explode_some(items, predicate, split):
for item in items:
if predicate(item):
yield from split(item)
else:
yield item
>>>
>>> print(list(
explode_some(
["apple", "pear"],
lambda x: x == "apple",
list
)
))
['a', 'p', 'p', 'l', 'e', 'pear']
You'd probably inline the predicate() and split() functions unless you
need them to be configurable in your actual use case.
More information about the Tutor
mailing list