Let's say I have the following list of lists:
[['Hello im an item', 1234], ['I enjoy python', 'hello'], ['I only have one item']]
I want to replace the spaces with underscores in the first item in each inner list so it looks like this:
[['Hello_im_an_item', 1234], ['I_enjoy_python', 'hello'], ['I_only_have_one_item']]
I have tried the following with no success:
formatted = [first[0].replace(' ', '_') for first in formatted]
formatted returns a list of only the first items, but with the correct formatting. Does anyone have any idea how this can be accomplished?
A list comprehension builds an entirely new list, so you need to ensure that that new list contains everything the old list contained. Concatenate the remainder of each sublist:
formatted = [[sub[0].replace(' ', '_')] + sub[1:] for sub in formatted]
As a regular for loop, the above is roughly equivalent to:
_new = []
for sub in formatted:
_element = [sub[0].replace(' ', '_')] + sub[1:]
_new.append(_element)
formatted = _new
Rather than use a list comprehension, you could just alter your list in-place with a regular loop:
for sub in formatted:
sub[0] = sub[0].replace(' ', '_')
Only use the list comprehension if you absolutely need a completely new list.
Just use a for loop:
for a in formatted:
a[0] = a[0].replace(' ', '_')
This really isn't a use-case for list comprehensions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With