height, width, device = 99, 99, 99
num_pieces = 3
#create datastructure to hold piece dimensions*
pieces = [[height, width, device]]
for i in range(num_pieces - 1):
pieces = pieces.append([0,0,0])
print "initial list"
print pieces
#get dimentions for the rest of the list starting at second element*
for i in pieces[1: ]:
print "list in loop"
print pieces
# get height of the ith piece
print "please enter the height of piece %d" % (pieces.index(i)+1)
height = float(raw_input(">>"))
# get width of the ith piece
print "please enter the width of piece %d" % (pieces.index(i)+1)
width = float(raw_input(">>"))
# get device of the ith piece
print "please enter the hanging device of piece %d" % (pieces.index(i)+1)
device = float(raw_input(">>"))
# test if element is empty
if i == [0,0,0]:
i = [height, width, device]
#view completeled list of dimensions
print pieces
我认为.append
有问题(我不应该使用.extend
吗?)
这是我的错误。我知道[1: ]
也有问题,但首先我想找出如何修复.append问题。
File "l_long.py", line 36, in <module>
for i in pieces[1: ]:
TypeError: 'NoneType' object has no attribute '__getitem__'
答案 0 :(得分:4)
由于此行,您收到错误:
pieces = pieces.append([0,0,0])
将pieces
的值设置为None
,因为列表append()
方法有效地返回该值。大多数就地更改关联容器对象的容器方法都不会返回任何内容(Python看起来好像返回了值None
)。
在您的代码中,这意味着pieces
在第一次迭代后将其值更改为:
for i in range(num_pieces - 1)
...因此,您发现TypeError
。
将行更改为:
pieces.append([0,0,0])
那个错误应该消失。
答案 1 :(得分:0)
我不知道你要做什么,但你的代码中存在一些缺陷:
pieces = [[height, width, device]]
# Here 'height', 'width', and 'device' must be defined, else you will get NameError.
num_pieces # Must defined. It may be the length of the list??
pieces = pieces.append([0,0,0]) # This is going to override your list
答案 2 :(得分:-1)
您的代码中存在一些错误我已在每次更正时使用注释更正了这些错误。检查这个,我认为这解决了你的问题: -
height=0
width=0
device=0
num_pieces=10
# you need to provide initialisation with above fields in your program which is required
pieces = [[height, width, device]]
for i in range(num_pieces - 1):
'''in your code line below returns null and when pieces become
null it has no attribute append '''
# pieces=pieces.append([0,0,0])
pieces.append([0,0,0])
#print pieces
j=0
for i in pieces[:]:
# get height of the ith piece
#print "please enter the height of piece %d"
#height = float(raw_input(">>"))
'''you can have user provided values
i have hard coded the values for
height width and device for the
time being for simplicity '''
height=10
# get width of the ith piece
#print "please enter the width of piece %d"
#width = float(raw_input(">>"))
width=10
# get device of the ith piece
# print "please enter the hanging device of piece %d"
#device = float(raw_input(">>"))
device=100
# test if element is empty
if i == [0,0,0]:
i = [height, width, device]
if j <= len(pieces):
# in your code no need for (pieces.index(i)+1)
pieces[j]=i
j=j+1
##view completeled list of dimensions
print pieces