你如何在python中找到带引号的数字列表的平均值?

Jon*_*ies 3 python unix linux

我有两种类型的列表.第一个没有引号,工作和打印平均罚款:

l = [15,18,20]
print l
print "Average: ", sum(l)/len(l)
Run Code Online (Sandbox Code Playgroud)

这打印:

[15,18,20]
Average: 17
Run Code Online (Sandbox Code Playgroud)

第二个列表包含引号的数字,返回错误:

x = ["15","18","20"]
print x
print "Average: ", sum(x)/len(x)
Run Code Online (Sandbox Code Playgroud)

错误是:

TypeError: unsupported operand type(s) for +: 'int' and 'str'
Run Code Online (Sandbox Code Playgroud)

如何计算数字值在引号内的列表?

iCo*_*dez 9

引号表示您有一个字符串列表:

>>> x = ["15","18","20"]
>>> type(x[0])
<type 'str'>
>>>
Run Code Online (Sandbox Code Playgroud)

sum仅适用于数字列表(如整数1或浮点数等1.0).

要解决您的问题,您必须先将您的字符串列表转换为整数列表.您可以使用内置map函数:

x = ["15","18","20"]
x = map(int, x)
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用列表理解(许多Python程序员更喜欢):

x = ["15","18","20"]
x = [int(i) for i in x]
Run Code Online (Sandbox Code Playgroud)

以下是演示:

>>> x = ["15","18","20"]
>>> x = map(int, x)
>>> x
[15, 18, 20]
>>> type(x[0])
<type 'int'>
>>> sum(x) / len(x)
17
>>>
Run Code Online (Sandbox Code Playgroud)