Reputation: 471
This my code:
num= [2,10]
def calculo(lista):
lista2 = []
for i in lista:
for j in range(1, i + 1):
if i % j == 0:
lista2.append(j)
return lista2
print(calculo(num))
Which produces: [1, 2, 1, 2, 5, 10].
However, I need the following result:
[[1, 2], [1, 2, 5, 10]]
In addition, I would like to know your approach through list comprehension.
Upvotes: 1
Views: 58
Reputation: 152
if you want to use list comprehension
[[x for x in range(1, n+1) if n%x==0] for n in num]
Upvotes: 2
Reputation: 5730
num = [2,10]
def calculo(lista):
result = [[j for j in range(1, i + 1) if i % j == 0] for i in lista]
return result
print(calculo(num))
Output:
[[1, 2], [1, 2, 5, 10]]
Upvotes: 1
Reputation: 114310
You need to make the nested lists before the nested loop, just like you make the outer list before the outer loop:
num = [2,10]
def calculo(lista):
lista2 = []
for i in lista:
lista3 = []
for j in range(1, i + 1):
if i % j == 0:
lista3.append(j)
if lista3:
lista2.append(lista3)
return lista2
print(calculo(num))
Any time you have a sufficiently simple loop that appends items to a list, you can turn it into a list comprehension. For example, the inner loop becomes:
lista3 = [j for j in range(1, i + 1) if i % j == 0]
Now you can write the entire function as:
def calculo(lista):
return [[j for j in range(1, i + 1) if i % j == 0] for i in lista]
Upvotes: 1
Reputation: 8010
You will need to create a new list for every iteration of the loop:
outer_list = []
for i in lista:
inner_list = []
for j in range(...):
if ...:
inner_list.append(...)
outer_list.append(inner_list)
return outer_list
Upvotes: 2
Reputation: 914
This will foreach i
loop append new list and then append new values to the last list
num= [2,10]
def calculo(lista):
lista2 = []
for i in lista:
lista2.append([])
for j in range(1, i + 1):
if i % j == 0:
lista2[-1].append(j)
return lista2
print(calculo(num))
Also in short form:
num= [2,10]
def calculo(lista):
lista2 = [[j for j in range(1, i+1) if i % j == 0] for i in lista]
return lista2
print(calculo(num))
Upvotes: 2