简体   繁体   中英

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. 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:

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) :

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 :

>> import ast

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

[1,2,3,4]

Detail about literal_eval( )

You can handle parsing the string data in numerous ways. 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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