Explanation of how nested list comprehension works?

前端 未结 8 1329
情书的邮戳
情书的邮戳 2020-11-22 02:06

I have no problem for understanding this:

a = [1,2,3,4]
b = [x for x in a]

I thought that was all, but then I found this snippet:



        
8条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 02:44

    Yes, you can nest for loops INSIDE of a list comprehension. You can even nest if statements in there.

    dice_rolls = []
    for roll1 in range(1,7):
        for roll2 in range(1,7):
            for roll3 in range(1,7):
                dice_rolls.append((roll1, roll2, roll3))
    
    # becomes
    
    dice_rolls = [(roll1, roll2, roll3) for roll1 in range(1, 7) for roll2 in range(1, 7) 
                  for roll3 in range(1, 7)]
    

    I wrote a short article on medium explaining list comprehensions and some other cool things you can do with python, you should have a look if you're interested : )

提交回复
热议问题