Understanding Python List Comprehension equivalent

2019-09-17 11:26发布

问题:

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("_")for el in listOfStrings]]

the result of this is:

['IAmExercising', 'PythonFunctional', 'ListsComprehension']

reading the documentation, i got the equivalent extended version, which puts the first expression in a variable to be appended and the second expression in a list to be iterated with the for statement:

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

but if i want write the same code without any list comprehension, how is the best way to do this? i tried with the following code, which works well:

returned = []
temp = []

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

but i didn't completely understood how to do this (transform the list comprehension to an equivalent full extended form)

回答1:

You can easily convert from outwards to inwards:

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

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

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

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

result = []
temp1 = []
for el in listOfStrings:
    temp1.append(el.split("_"))
for split in temp1:
    temp2 = []
    for elem in split:
        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)


回答2:

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() for splited in el.split("_")]) for el in listOfStrings]