简体   繁体   English

在Python中将“ [1,2,3,4]”转换为浮点数或整数

[英]converting a '[1,2,3,4]' to a float or int in python

Hi so I am trying to find the avg of a list We have to make a function so I have 嗨,所以我试图找到一个列表的平均值。

def avgLst():
    'str==>avg of numbers in str'
    x=input('Please enter a List: ')

    if len(x)==0:
        return([])

It is from this point I am having trouble. 从这一点来看,我遇到了麻烦。 I am trying to find to avg of the input we put into the problem. 我试图寻找我们投入到问题中的平均意见。 something like[1,2,3,4] problem is this list is a string because of the input. 像[1,2,3,4]之类的问题是此列表由于输入而为字符串。 How do I get the list to be a list of integers or floats to then find the avg of the list? 如何获取列表为整数或浮点数的列表,然后查找列表的平均值? Thanks, 谢谢,

You can use ast.literal_eval here: 您可以在此处使用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]

help(literal_eval) : 帮助(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.

You can process your input as follows: 您可以按以下方式处理输入:

def input_to_list(input_str):
    input_list = input_str[1:-1].split(",")
    return map(int, input_list)

Use literal_eval( ) in ast (Abstract Syntax Trees) module : ast(抽象语法树)模块中使用literal_eval()

>> import ast

>> yrStrList = '[1,2,3,4]'
>> yrList = ast.literal_eval(yrlist)
>> print yrList

[1,2,3,4]

Detail about literal_eval( ) 有关literal_eval( ) 详细信息

You can handle parsing the string data in numerous ways. 您可以通过多种方式处理string数据的解析。 I haven't tested this function for speed but one way you could do this is: 我尚未测试此功能的速度,但是可以执行以下操作的一种方法是:

def list_avg(str_list):
    int_list = [float(i.strip('[]')) for i in str_list.split(',')]
    return sum(int_list) / len(int_list)

If I understand correctly what you are asking, then list_avg will return a float average of the integers in str_list . 如果我正确理解您的要求,则list_avg将返回str_list整数的float平均值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM