Python for in loop to generate dictionary

I came across this snippet of code, I understand it's a Cartesian product but if someone can break up this line for me [s+t for s in a for t in b] from the following code along with docs link for this kind of syntax.

Apparently this for in syntax with s+t ??? is foreign for me and I'm new to python as well. Appreciate docs link so I can understand more about this syntax since there are other variations of for in loops that I'm trying to understand.

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()

This is a shorthand syntax known as a list comprehension. See section 5.1.4 of the docs: https://docs.python.org/2/tutorial/datastructures.html

The line is exactly equivalent to this:

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

It just finds the sums of every pair of an element in a and an element in b .


It can be broken down into:

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

Hope this helps!

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

上一篇: Python列表理解item()和枚举()

下一篇: 用于循环生成字典的Python