Last active
February 6, 2020 16:10
-
-
Save radbrt/8715b0a14381130f8242197abc40f603 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# A list of lists | |
ll = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]] | |
# flatten to single list | |
[n for li in ll for n in li] | |
# Corresponds to: | |
for li in ll: | |
for n in li: | |
print(n) # list2.append(n) | |
# Notice the order is the same in loops as in list comprehensions; | |
# First, iterate through list of lists (for li in ll), second, iterate through elements in list. | |
# The only difference is where the elements are returned. | |
# Flatten list but with conditions | |
[n for li in ll if len(li)<4 for n in li if n>3] | |
# Corresponds to | |
for li in ll: | |
if len(li)<4: | |
for n in li: | |
if n>3: | |
print(n) | |
# List of lists of lists | |
lll = [[[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]], [[-1, -2, -3], [-4, -5, -6], [-7, -8, -9, -10]]] | |
# flatten: | |
[n for ll in lll for li in ll for n in li] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment