List of lists as a result of list comprehension
I am trying to find a solution for a problem where I need to loop through a list for each item.
This is not the real problem I am trying to solve, but I am using a simple example to illustrate the problem and what I want to understand.
aList= [3, 4, 5, 6, 8, 9, 10,12]
I have to rearrange the divisible numbers.
the result should give:
result = [[3], [4], [5], [6,3], [4,8],[3,9], [5,10], [3,4,6,12]]
I am using this function:
def divisible(x,y):
if x%y== 0:
return True
else:
return False
ok, to solve this problem using two loops we can use:
globaList= []
for x in aList:
internalist=[]
internalist.append(x)
for y in aList:
if divisible(x,y):
internalist.append(y)
globaList.append(internalist)
I tried to write this double loop in list comprehension but didn't know how to do the best way.
result= [[x for x in aList ] for y in aList if divisible(x,y) ]
+3
source to share