I'm trying to enter a 100 number square into a 2D list https://i.stack.imgur.com/eSFiO.png with each list containing 10 numbers 1-10,11-20,21-30 and so on. This is my code so far but when I run it in my editor it just keeps running and eventually crashes without printing anything. Please explain to me what I am doing wrong. Thanks
number_square=[[],[],[],[],[],[],[],[],[],[]]
number_list=[1,2,3,4,5,6,7,8,9,10]
for row in number_square:
for number in number_list:
number_square.append(number)
number_list.remove(number)
number_list.append(number+10)
print(number_square)
There are many changes required in your code. Good effort from your side on trying the code. I have modified the code and probably you can get the logic from it.
number_square=[[],[],[],[],[],[],[],[],[],[]]
number_list=[10,20,30,40,50,60,70,80,90,100]
for i in range(0,len(number_square)):
for j in range(number_list[i]-9,number_list[i]+1):
number_square[i].append(j)
Problems:
number_list
while iterating over itnumber_square
instead of row
If I were you, I'd use a list comprehension with range
s instead:
number_square = [list(range(i, i+10)) for i in range(1, 101, 10)]
Due credit to Onyambu for suggesting something similar in a comment
That's because you aren't accessing the content of neither row
nor number
in the for
loops. Here is a suggestion:
number_square=[[],[],[],[],[],[],[],[],[],[]]
number_list=[1,2,3,4,5,6,7,8,9,10]
i = 0
for row in number_square:
for i in range(len(number_list)):
row.append(number_list[i])
number_list[i] += 10
print(number_square)
Note that the first loop is equivalent to for each
. In this syntax, you can't alter the value of the item in a list. In the second loop, I put a "traditional" for
loop with range
to alter the values in number_list
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.