I have two types of lists. The first without quotes, which works and prints the average fine:
我有两种类型的列表。第一个没有引号,工作和打印平均罚款:
l = [15,18,20]
print l
print "Average: ", sum(l)/len(l)
This prints:
这打印:
[15,18,20]
Average: 17
The second list has numbers with quotes, which returns an error:
第二个列表的数字带引号,返回错误:
x = ["15","18","20"]
print x
print "Average: ", sum(x)/len(x)
The Error is:
错误是:
TypeError: unsupported operand type(s) for +: 'int' and 'str'
How do you calculate a list with number values within quotes?
如何计算数字值在引号内的列表?
3 个解决方案
#1
9
The quotes mean that you have a list of strings:
引号表示您有一个字符串列表:
>>> x = ["15","18","20"]
>>> type(x[0])
<type 'str'>
>>>
sum
only works with lists of numbers (integers such as 1
or floats such as 1.0
).
sum仅适用于数字列表(整数,如1或浮点数,如1.0)。
To fix your problem, you must first convert your list of strings into a list of integers. You can use the built-in map
function for this:
要解决您的问题,您必须先将您的字符串列表转换为整数列表。您可以使用内置的map函数:
x = ["15","18","20"]
x = map(int, x)
Or, you could use a list comprehension (which many Python programmers prefer):
或者,您可以使用列表理解(许多Python程序员更喜欢):
x = ["15","18","20"]
x = [int(i) for i in x]
Below is a demonstration:
以下是演示:
>>> x = ["15","18","20"]
>>> x = map(int, x)
>>> x
[15, 18, 20]
>>> type(x[0])
<type 'int'>
>>> sum(x) / len(x)
17
>>>
#2
3
you need to convert them to int
first:
你需要先将它们转换为int:
x = ["15","18","20"]
print sum(map(int,x))/len(x)
here map
will map every element of x to integer type
这里map将x的每个元素映射到整数类型
#3
2
print "Average of {list} is: {avg}".format(
list=l,
avg=sum(int(x) for x in l) / len(l),
)
#1
9
The quotes mean that you have a list of strings:
引号表示您有一个字符串列表:
>>> x = ["15","18","20"]
>>> type(x[0])
<type 'str'>
>>>
sum
only works with lists of numbers (integers such as 1
or floats such as 1.0
).
sum仅适用于数字列表(整数,如1或浮点数,如1.0)。
To fix your problem, you must first convert your list of strings into a list of integers. You can use the built-in map
function for this:
要解决您的问题,您必须先将您的字符串列表转换为整数列表。您可以使用内置的map函数:
x = ["15","18","20"]
x = map(int, x)
Or, you could use a list comprehension (which many Python programmers prefer):
或者,您可以使用列表理解(许多Python程序员更喜欢):
x = ["15","18","20"]
x = [int(i) for i in x]
Below is a demonstration:
以下是演示:
>>> x = ["15","18","20"]
>>> x = map(int, x)
>>> x
[15, 18, 20]
>>> type(x[0])
<type 'int'>
>>> sum(x) / len(x)
17
>>>
#2
3
you need to convert them to int
first:
你需要先将它们转换为int:
x = ["15","18","20"]
print sum(map(int,x))/len(x)
here map
will map every element of x to integer type
这里map将x的每个元素映射到整数类型
#3
2
print "Average of {list} is: {avg}".format(
list=l,
avg=sum(int(x) for x in l) / len(l),
)