Reputation: 5354
I am trying to find a solution for a problem where I have to loop in a list for every element.
This is not the real problem that 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 should regroup number divisible by each others.
result should give:
result = [[3], [4], [5], [6,3], [4,8],[3,9], [5,10], [3,4,6,12]]
I use this function:
def divisible(x,y):
if x%y== 0:
return True
else:
return False
well, 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-loops in list comprehension, but didn't know how to make better way.
result= [[x for x in aList ] for y in aList if divisible(x,y) ]
Upvotes: 3
Views: 72
Reputation: 2512
You don't really need a helper function divisible:
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 that more succinct by going:
def divisible(x,y):
return x % y == 0
Upvotes: 1
Reputation: 117971
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]]
Upvotes: 3