Skip to content Skip to sidebar Skip to footer

Understanding Python List Comprehension Equivalent

I have the following code: listOfStrings = ['i_am_exercising', 'python_functional', 'lists_comprehension'] [ ''.join([elem.title() for elem in splited]) for splited in [el.split('_

Solution 1:

You have both a nested list comprehensions, one inside the other, plus another one to create a list of split elements first. You can reduce this to just two loops instead:

returned = []
for el in listOfStrings:
    tmp = []
    for splited in el.split("_"):
        tmp.append(splited.title())
    returned.append("".join(tmp))

This simplifies back down to a list comprehension of the form:

["".join([splited.title() forsplitedin el.split("_")]) forelin listOfStrings]

Solution 2:

You can easily convert from outwards to inwards:

listOfStrings = ['i_am_exercising', 'python_functional', 'lists_comprehension']

result = [ "".join([elem.title() for elem insplit]) forsplitin [el.split("_")for el in listOfStrings]]
print result

result = []
forsplitin [el.split("_") for el in listOfStrings]:
    result.append("".join([elem.title() for elem insplit]))
print result

result = []
temp1 = []
for el in listOfStrings:
    temp1.append(el.split("_"))
forsplitin temp1:
    result.append("".join([elem.title() for elem insplit]))
print result

result = []
temp1 = []
for el in listOfStrings:
    temp1.append(el.split("_"))
forsplitin temp1:
    temp2 = []
    for elem insplit:
        temp2.append(elem.title())
    result.append("".join(temp2))
print result

Basically you just follow the following scheme:

result = [foo for bar in baz]

is turned into

result = []
for bar in baz:
    result.append(foo)

Post a Comment for "Understanding Python List Comprehension Equivalent"