0

我有以下代码:

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']

阅读文档,我得到了等效的扩展版本,它将第一个表达式放在要附加的变量中,将第二个表达式放在要使用 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))

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

4

2 回答 2

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]
于 2013-05-16T18:59:46.820 回答
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)
于 2013-05-16T19:13:51.887 回答