了解Python List Comprehension等效项 [英] Understanding Python List Comprehension equivalent
问题描述
我有以下代码:
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语句进行迭代的列表中:
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)
推荐答案
您可以轻松地从外向内转换:
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]
变成
result = []
for bar in baz:
result.append(foo)
这篇关于了解Python List Comprehension等效项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!