i am a newbie in programming.I have a problem with a list comprehension.i need divide a list in tuple with size 5,and my code work well,but if i have in input a list of lists ,i don't know how insert a double loop in list comprehension.i hope that someone can help me. this is my code:
big_list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
x = 5
bot = [tuple(big_list1[i: i x])for i in range(0, len(big_list1), x)]
and this is output:
bot=[(1, 2, 3, 4, 5), (6, 7, 8, 9, 10), (11, 12, 13, 14, 15)]
But if i have a list of lists like this:
my_list=[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [1, 2, 3, 4, 5]]
I would like to have this:
res=[[(1, 2, 3, 4, 5),(6, 7, 8, 9, 10),(11, 12, 13, 14, 15)], [(1, 2, 3, 4, 5),(6, 7, 8, 9, 10)], [(1, 2, 3, 4, 5)]]
i am confused because having "range" in the loop, i don't know how to do the nested loop.
CodePudding user response:
define as a function:
def split_in_tuples(input_list, tuple_length):
return [tuple(input_list[i: i tuple_length]) for i in range(0, len(input_list), tuple_length)]
which you can then use like:
big_list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
split_in_tuples(big_list1, 5)
gives
[(1, 2, 3, 4, 5), (6, 7, 8, 9, 10), (11, 12, 13, 14, 15)]
then for your list of lists you can:
my_list=[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [1, 2, 3, 4, 5]]
[split_in_tuples(sublist, 5) for sublist in my_list]
which gives:
[[(1, 2, 3, 4, 5), (6, 7, 8, 9, 10), (11, 12, 13, 14, 15)], [(1, 2, 3, 4, 5), (6, 7, 8, 9, 10)], [(1, 2, 3, 4, 5)]]
CodePudding user response:
If you want to use list comprehension, you can do it like this (given my_list
and x
from the stated question):
[[tuple(l[i: i x]) for i in range(0, len(l), x)] for l in my_list]
CodePudding user response:
If you really want to use a list comprehension the you can do it as follows:
[[tuple(elem[i: i x]) for i in range(0, len(elem), x)] for elem in my_list]
CodePudding user response:
Maybe the final code is no so 'cool' anyway your code is not so far from the solution, you must add the external loop (in my solution I've used the same example with same naming) Maybe this can be useful
my_list=[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [1, 2, 3, 4, 5]]
x = 5
[[tuple(big_list1[i: i x])for i in range(0, len(big_list1), x)] for big_list1 in my_list]
# [[(1, 2, 3, 4, 5), (6, 7, 8, 9, 10), (11, 12, 13, 14, 15)],
[(1, 2, 3, 4, 5), (6, 7, 8, 9, 10)],
[(1, 2, 3, 4, 5)]]
that is what you want.
hint
More in general, nesting lc requires a little hint. suppose you need to nest 2 list comprehension, the first approach is this:
c = ['ab']
[a for a in b for b in c]
but this doesn't work NameError: name 'b' is not defined
because the resolution order of python,
but reordering in the right way, from right to left
[a for b in c for a in b]
run as expected.