I have three items in a list of lists:
test = [[a,b,c],[d,e,f],[g,h,i]]
I want it to look like this:
test = [[a,b,c,d,e,f],[g,h,i]]
what is the best way to do this in python?
Thanks for the help
I have three items in a list of lists:
test = [[a,b,c],[d,e,f],[g,h,i]]
I want it to look like this:
test = [[a,b,c,d,e,f],[g,h,i]]
what is the best way to do this in python?
Thanks for the help
>>> test = [[1,2,3], [4,5,6], [7,8,9]]
>>> test[0].extend(test.pop(1)) # OR test[0] += test.pop(1)
>>> test
[[1, 2, 3, 4, 5, 6], [7, 8, 9]]
If you want to flatten of an arbitrary slice, use a slice assignment and a list comprehension on the part you want to flatten.
This flatten from position n
to end of the list:
>>> test = [[1,2,3],[4,5,6],[7,8,9],[10,11,12],[13,14,15]]
>>> n=2
>>> test[n:]=[[i for s in test[n:] for i in s]]
>>> test
[[1, 2, 3], [4, 5, 6], [7, 8, 9, 10, 11, 12, 13, 14, 15]]
This flattens up to n
(but including n
):
>>> test = [[1,2,3],[4,5,6],[7,8,9],[10,11,12],[13,14,15]]
>>> test[0:n]=[[i for s in test[0:n] for i in s]]
>>> test
[[1, 2, 3, 4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15]]
This flattens in the middle (from and including n
to include the additional groups specified):
>>> test = [[1,2,3],[4,5,6],[7,8,9],[10,11,12],[13,14,15]]
>>> test[n:n+2]=[[i for s in test[n:n+2] for i in s]]
>>> test
[[1, 2, 3], [4, 5, 6], [7, 8, 9, 10, 11, 12], [13, 14, 15]]
Flatten all the sublists:
>>> test = [[1,2,3],[4,5,6],[7,8,9],[10,11,12],[13,14,15]]
>>> n=len(test)
>>> test[0:n]=[[i for s in test[0:n] for i in s]]
>>> test
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]]
Note that in each case the slice on the assignment side is the same as the slice on the list comprehension side. This allows the use of the same slice object for each.
For the last case of flattening the whole list, obviously, you can just do test=[[i for s in test for i in s]]
but the fact the logic is consistent allows you to wrap this in a function use a slice object.
You could combine the first two items in the list of list with the +
operator and you should use ''
for your strings
test = [['a','b','c'],['e','f','g'],['h','i','j']]
result = [test[0] + test[1], test[2]]
print result
output:
[['a', 'b', 'c', 'e', 'f', 'g'], ['h', 'i', 'j']]
Using the more_itertools
package:
import more_itertools as mit
list(mit.chunked(mit.flatten(test), 6))
# [[1, 2, 3, 4, 5, 6], [7, 8, 9]]