0
How do you add two lists together using nested loop?
I want it like the list below. How is this index out of range? first = [1, 8, 27, 64, 125] second = [1, 8, 27, 64, 125] def sum_cube(): total_cubes = [] for i in range(len(first)): for j in range(len(second)): total = first[i] + second[j] total_cubes.append(total) second.remove(second[j])
6 ответов
+ 1
What is the expected result in <total_cubes>?
+ 1
Like this?
[ 2, 16, 54, 128, 250 ]
For this you can use list comprehension combined with use of zip() function.
If it's not what you expected, then an example result may help me understand.
0
first.extend(second)
0
Two cubes added together that is put into a list
0
[2, 9, 28, 16, 35, 28, 54]
the sum of two cubes with none repeated
0
"""
what do you mean by "with none repeated", as your list before contains twice the number 28?
"""
def sum_cube(n):
cubes = [*map(lambda x: x*x*x,range(1,n+1))]
print(cubes)
res = []
for v in cubes:
for u in cubes:
"""
# uncomment block to not repeat
# and comment last line instead
u += v
if not u in res:
res.append(u)
"""
res.append(u+v)
return res
print(sum_cube(3))
"""
output without changing comment:
[2, 9, 28, 16, 35, 28, 54]
with uncomment (and comment last function line):
[2, 9, 28, 16, 35, 54]
"""