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


2 answers


def divisible(x,y):
    if x%y== 0: 
        return True
    else: 
        return False

aList= [3, 4, 5, 6, 8, 9, 10,12]

>>> [[x for x in aList if divisible(y,x)] for y in aList]
[[3], [4], [5], [3, 6], [4, 8], [3, 9], [5, 10], [3, 4, 6, 12]]

      



+3


source


You don't really need a helper function:

aList= [3, 4, 5, 6, 8, 9, 10,12]
print [[x for x in aList if y % x == 0] for y in aList]

      



If you really want to use a helper function, you can make it more concise by going:

def divisible(x,y):
    return  x % y == 0

      

+1


source







All Articles