Home > OS >  How to conditionally split and extend inside a list comprehension?
How to conditionally split and extend inside a list comprehension?

Time:11-18

How do I convert this input:

values = ['v1,v2', 'v3']

to this output:

['v1', 'v2', 'v3']

Attempt without list comprehension that works:

values = ['v1,v2', 'v3']
parsed_values = []

for v in values:
    if ',' in v:
        parsed_values.extend(v.split(','))
    else:
        parsed_values.append(v)

print(parsed_values)    # ['v1', 'v2', 'v3']

Attempt with list comprehension that does not work:

parsed_values = [_ for _ in [v.split(',') if ',' in v else v for v in values]]
# [['v1', 'v2'], 'v3']

CodePudding user response:

You don't care if there is a comma or not, splitting on it will always give a list you can iterate on

values = ['v1,v2', 'v3']
parsed_values = [word for value in values for word in value.split(",")]
print(parsed_values)
# ['v1', 'v2', 'v3']

CodePudding user response:

Try:

values = ["v1,v2", "v3"]

values = ",".join(values).split(",")
print(values)

Prints:

['v1', 'v2', 'v3']
  • Related