我有两种类型的列表。第一个没有引号,工作并打印平均罚款:
l = [15,18,20]
print l
print "Average: ", sum(l)/len(l)
打印:
[15,18,20]
Average: 17
第二个列表的数字带引号,返回错误:
x = ["15","18","20"]
print x
print "Average: ", sum(x)/len(x)
错误是:
TypeError: unsupported operand type(s) for +: 'int' and 'str'
如何计算数字值在引号内的列表?
答案 0 :(得分:9)
引号表示您有一个字符串列表:
>>> x = ["15","18","20"]
>>> type(x[0])
<type 'str'>
>>>
sum
仅适用于数字列表(整数,如1
或浮点数,如1.0
)。
要解决您的问题,您必须先将字符串列表转换为整数列表。您可以使用内置的map
function:
x = ["15","18","20"]
x = map(int, x)
或者,您可以使用list comprehension(许多Python程序员更喜欢):
x = ["15","18","20"]
x = [int(i) for i in x]
以下是演示:
>>> x = ["15","18","20"]
>>> x = map(int, x)
>>> x
[15, 18, 20]
>>> type(x[0])
<type 'int'>
>>> sum(x) / len(x)
17
>>>
答案 1 :(得分:3)
您需要先将它们转换为int
:
x = ["15","18","20"]
print sum(map(int,x))/len(x)
此处map
会将x的每个元素映射到整数类型
答案 2 :(得分:2)
print "Average of {list} is: {avg}".format(
list=l,
avg=sum(int(x) for x in l) / len(l),
)