在Python代码中无法用非整数类型'list'乘以序列

0 投票
2 回答
876 浏览
提问于 2025-04-20 14:10

我正在把一个C语言的程序转换成Python,但出现了一个错误。我哪里做错了呢?

# -*-coding:utf-8 -*-

datos=open("bio.dat","r+")

h=[];numero=[];edad=[];peso=[]

nombre=[]
#Creando matriz para nombre
for i in range(100):
   nombre.append([0]*50)


apellido=[]
#Creando matriz para apellido
for i in range(100):
  apellido.append([0]*50)

 sexo=[]
 #Creando matriz para sexo
 for i in range(100):
   sexo.append([0]*50)


sumah=[];sumap=[];sumahp=[];sumah2=[]

for l in xrange(1,26):
 h+=[l]
 sumah+=h
 peso+=[l]
 sumap+=peso
 sumahp+=h*peso
 sumah2+=h*h

promh=sumah/25.0
promp=sumap/25.0

a=(sumah*sumap-25*sumahp)/(sumah2-25*sumah*sumah)
b=promp-a*promh

这是我遇到的错误:

 File "datobiometrico.py", line 34, in <module>
 sumahp+=h*peso
 TypeError: can't multiply sequence by non-int of type 'list'

2 个回答

0

在Python中,有一件事情是大家还没提到的,那就是尽量避免在列表上使用 +=。你可以用 append()extend() 来代替。它们的工作原理是这样的:

mylist = [1,2,3,4]
mylist.append(5)
# mylist is now [1,2,3,4,5]
otherlist = [6,7,8]
mylist.extend(otherlist)
# mylist is now [1,2,3,4,5,6,7,8]

append() 方法只需要一个参数,它会把这个参数添加到列表的末尾。而 extend() 方法也需要一个参数,这个参数应该是一个 序列,比如另一个列表,它会把那个序列里的每一个项目逐个添加到你的原始列表中。那它们有什么区别呢?如果你把一个列表传给 append() 方法,它只会把这个列表作为一个整体添加到你的列表中,变成列表里的一个条目。看看这个例子:

list_a = [1,2,3,4]
list_b = [1,2,3,4]

list_a.append([5,6,7])
# list_a is now [1,2,3,4,[5,6,7]]
print len(list_a) # This will be 5
print list_a[-1] # This will print the list [5,6,7]

list_b.extend([5,6,7]
# list_b is now [1,2,3,4,5,6,7]
print len(list_b) # This will be 7
print list_b[-1] # This will print the integer 7

我为什么要提这个呢?因为你现在在列表上使用 +=,这和 extend() 方法的效果是一样的。所以你的代码像是 h+=[l],这和 h.extend([l]) 是一样的,都是把一个单独的项目添加到列表里。但其实用 h.append(l) 会更好,因为这样能更清楚地表达你的代码想要做什么。

1

很明显,这个列表是空的:

h=[]

你需要先往里面添加25个元素,代码才能正常运行(顺便提一下:列表的索引是从0开始的,而不是像你代码里暗示的那样从1开始)。你可以这样做:

h.append(firstValue)
h.append(secondValue)
# and so on

在Python中,列表一开始是没有任何元素的,也就是说它们没有值——这和其他编程语言里的数组不一样,后者一开始是有固定长度的。Python中的列表一开始长度为零,所以即使你想用h[0]来访问元素,也会失败,除非你先添加元素,比如使用append()方法。

更新

所以,你想把一些C语言的代码转换成Python。你的方法是错的,你把numbers初始化成了列表,而且你访问元素的方式也不对。下面是C语言代码在Python中的样子:

sumah  = 0
sumap  = 0
sumahp = 0
sumah2 = 0

for i in xrange(1, 26):
    sumah  += h[i]
    sumap  += peso[i]
    sumahp += h[i]*peso[i]
    sumah2 += h[i]*h[i]

撰写回答