Skip to main content
 首页 » 编程设计

python之在 python 中将 '[1,2,3,4]' 转换为 float 或整数

2025年05月04日10wuhuacong

你好,我正在尝试查找列表的平均值 我们必须做一个函数,所以我有

def avgLst(): 
    'str==>avg of numbers in str' 
    x=input('Please enter a List: ') 
 
    if len(x)==0: 
        return([]) 

正是从这一点开始,我遇到了麻烦。 我试图找到我们投入问题的输入的平均值。 类似 [1,2,3,4] 的问题是这个列表是一个字符串,因为输入。如何让列表成为整数或 float 的列表,然后找到列表的平均值? 谢谢,

请您参考如下方法:

你可以在这里使用ast.literal_eval:

In [6]: strs="[1,2,3,4]" 
 
In [7]: from ast import literal_eval 
 
In [9]: literal_eval(strs) 
Out[9]: [1, 2, 3, 4] 

帮助(literal_eval):

In [10]: literal_eval? 
Type:       function 
String Form:<function literal_eval at 0x8cb7534> 
File:       /usr/lib/python2.7/ast.py 
Definition: literal_eval(node_or_string) 
Docstring: 
Safely evaluate an expression node or a string containing a Python 
expression.  The string or node provided may only consist of the following 
Python literal structures: strings, numbers, tuples, lists, dicts, booleans, 
and None.