简体   繁体   English

填充二维列表

[英]Populating a 2D list

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.我正在尝试将 100 个数字方块输入 2D 列表https://i.stack.imgur.com/eSFiO.png ,每个列表包含 10 个数字 1-10,11-20,21-30 等等。 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:问题:

  1. Removing from number_list while iterating over it在迭代它时number_list中删除
  2. Appending to number_square instead of row附加到number_square而不是row

If I were you, I'd use a list comprehension with range s instead:如果我是你,我会使用带有range列表推导:

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由于Onyambu评论中提出了类似的建议

That's because you aren't accessing the content of neither row nor number in the for loops.那是因为您没有访问for循环rownumber的内容。 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 .请注意,第一个循环等效于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 .在第二个循环中,我放置了一个带有range的“传统” for循环来更改number_list中的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM