理解Python List Comprehension等价物

时间:2013-05-16 18:56:49

标签: python nested list-comprehension

我有以下代码:

listOfStrings = ['i_am_exercising', 'python_functional', 'lists_comprehension']
[ "".join([elem.title() for elem in splited]) for splited in [el.split("_")for el in listOfStrings]]

结果是:

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

阅读documentation,我得到了等效的扩展版本,它将第一个表达式放在要追加的变量中,第二个表达式放在列表中,用for语句迭代:

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

但如果我想编写相同的代码而没有任何列表理解,那么最好的方法是如何做到这一点?我尝试使用以下代码,效果很好:

returned = []
temp = []

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

但是我并没有完全理解如何做到这一点(将列表理解转换为等效的完整扩展形式)

2 个答案:

答案 0 :(得分:2)

你有一个嵌套的列表推导,一个在另一个里面,另外一个用于创建一个拆分元素列表。您可以将其减少为仅两个循环:

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

这简化了对表单的列表理解:

["".join([splited.title() for splited in el.split("_")]) for el in listOfStrings]

答案 1 :(得分:0)

您可以轻松地从外向内转换:

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

基本上你只需遵循以下方案:

result = [foo for bar in baz]

变成了

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