+ 8
Flatten the list in one line (challenge)
Here's a little challenge: Convert this: list = [[1, 2, 3], [4, 5, 6], [7], [8, 9]] to this: [1, 2, 3, 4, 5, 6, 7, 8, 9] with one line of code. (not counting the first line, which is list = [[1, 2, 3], [4, 5, 6], [7], [8, 9]])
14 Réponses
+ 4
+ 4
VcC has the one I was thinking of but Tim's works fine too!
+ 4
print([element for sublist in list for element in sublist])
is shorthand for
newlist = []
for sublist in list:
for element in sublist:
newlist.append(element)
print(newlist)
https://code.sololearn.com/c8AzvmAQv5yc/#py
+ 4
Another way is simply:
print(sum(list, [])
but this is apparently slower.
+ 4
@VcC your cool code suggests that it is not slower. I got that idea from https://mathieularose.com/how-not-to-flatten-a-list-of-lists-in-JUMP_LINK__&&__python__&&__JUMP_LINK/
+ 3
Another one
https://code.sololearn.com/cIJahh32SNpZ/?ref=app
+ 3
@Eric sum() is just a built-in function that adds the elements of an iterable.
E.g.
this_list = [1, 2, 3, 4]
print(sum(this_list))
# outputs 10
sum(list, []) adds (concatenates) the lists in 'list'
so in the challenge example, print(sum(sum(Iist, []))) yields 45
+ 2
@VcC kindly explain your code for me
+ 1
I've got oneliner here!
https://code.sololearn.com/c1f6tbapyHL1/?ref=app
0
You take each element from each sib list of the main list, and make a list out of this !
0
Why isit slower?
0
Don't see such a big difference, see here. In fact the sum version looks faster
https://code.sololearn.com/cHxS7O7vr4nD/?ref=app
0
The difference is 100% to 200% ( with an improved version of chrono which deducts the duration of the call to an empty function) - so the sum version is indeed slower... What is funny is that the multiple line naive version with a for loop is much faster ! Interesting article.