Python"NoneType"错误

我想打印出不带零的清单,以使其更具可读性。
这段代码的一部分在While循环中。

选择 | 换行 | 行号
  1. import copy
  2. pieces = [ [1,2,3,4,5,6] , [0,0,0,0,0,0], [0,0,0,0,0,0] ]
  3. def formatt (formatt) :
  4.         while 0 in formatt[1] :
  5.                 formatt[1].remove(0)
  6.         while 0 in formatt[2] :
  7.                 formatt[2].remove(0)
  8.         while 0 in formatt[0] :
  9.                 formatt[0].remove(0)
  10.         print formatt
  11.  
  12.         #part in loop \/
  13.         form = copy.deepcopy(pieces)
  14.         formatt(form)
  15.  

但是在循环运行一次之后,我收到了这个错误消息:
回溯(最近一次呼叫):
文件"C:\Documents and Settings\JOS\Desktop\Towers of Henoy.py",第68行,中
格式(表单)
文件"C:\Documents and Settings\JOS\Desktop\Towers of Henoy.py",第37行,格式
格式为[1]时为0:
TypeError:'NoneType'对象不可订阅
有人能帮忙吗?
-谢谢
马赫姆1

# 回答1


这可以通过列表理解来更简洁地完成:

选择 | 换行 | 行号
  1. >>> pieces = [ [1,2,3,4,5,6] , [0,0,0,0,0,0], [0,0,0,0,0,0] ]
  2. >>> [[num for num in item if num != 0] for item in pieces]
  3. [[1, 2, 3, 4, 5, 6], [], []]
  4. >>> 
# 回答2


这太好用了!!
错误:
'TypeError:'NoneType'对象不可订阅'/Iterable
是因为我用了'返回片断'而不是'返回片断'。
-谢谢
马赫姆1
# 回答3


我怀疑这是因为您为函数和变量使用了相同的名称(您在代码中引用的是哪一个)。变量的类型为字符串、整型等。函数可能为NONE类型。

选择 | 换行 | 行号
  1. def formatt (formatt) : 

标签: python

添加新评论