用于循环生成字典的Python

我遇到了这段代码,我知道这是一个笛卡尔积,但如果有人能够为我分解这一行[s+t for s in a for t in b]下面的代码中的[s+t for s in a for t in b] ,以及这种语法的docs链接。

显然,这for in带语法s+t ??? 对我来说是陌生的,我也是python的新手。 欣赏文档链接,所以我可以更多地了解这种语法,因为我试图理解的循环中还有其他变体。

rows = 'ABCDEFGHI'
cols = '123456789'

def cross(a, b):
    return [s+t for s in a for t in b]

def main():
    print(cross(rows, cols))

if __name__ == "__main__": main()

这是一种称为列表理解的简写语法。 请参阅文档的第5.1.4节:https://docs.python.org/2/tutorial/datastructures.html

该行完全等同于:

lst = []
for s in a:
    for t in b:
        lst.append(s+t)
return lst

它只是在发现每对的元素的的总和a和中的一个元素b


它可以分解为:

lst = []
for s in A:
    for t in b:
        lst.append(s+t)
return lst

希望这可以帮助!

链接地址: http://www.djcxy.com/p/69961.html

上一篇: Python for in loop to generate dictionary

下一篇: python 2.7 for loop to generate a list