mean of items in a weird list [duplicate] - python

This question already has answers here:
How can I convert a string with dot and comma into a float in Python
(9 answers)
Closed 6 years ago.
I have a list in python and I want to get the average of all items. I tried different functions and even I wrote a small function for that but could not do that. even when I tried to convert the items to a int or float it gave these errors:
TypeError: float() argument must be a string or a number
TypeError: int() argument must be a string or a number, not 'list'
here is a small example of my list in python.
['0,0459016', '0,0426647', '0,0324087', '0,0222222', '0,0263356']
do you guys know how to get the average of items in such list/
thanks

Assuming that '0,0459016' means '0.0459016':
In [6]: l = ['0,0459016', '0,0426647', '0,0324087', '0,0222222', '0,0263356']
In [7]: reduce(lambda x, y: x + y, map(lambda z: float(z.replace(',', '.')), l)) / len(l)
Out[7]: 0.033906559999999995

Please refer to How can I convert a string with dot and comma into a float number in Python
sum([float(v.replace(",", ".")) for v in a]) / len(a)
where a is your original list.

Try this,
In [1]: sum(map(float,[i.replace(',','.') for i in lst]))/len(lst)
Out[1]: 0.033906559999999995
Actulluy there is 2 problem in your list. The elements are string and instead of . it having ,. So we have to convert to normal form. like this.
In [11]: map(float,[i.replace(',','.') for i in lst])
Out[11]: [0.0459016, 0.0426647, 0.0324087, 0.0222222, 0.0263356]
Then perform the average.

Related

How do you convert a string containing an operation into a numerical value [duplicate]

This question already has answers here:
Evaluating a mathematical expression in a string
(14 answers)
Closed 1 year ago.
I need to convert a string variable in the form of 'x / y', where x and y are arbitrary values in this string, into a numerical value. I'd assume that, using python, simply doing float('x/y') would allow for the interpretation of the division operation and thus yield a numerical value as the response, but instead, I am met with the following error:
ValueError: could not convert string to float: '7/100' (7 and 100 were the arbitrary values here)
Which suggests that this method is invalid. Is there any other way of doing this ? I thought of converting 'x' into an integer, then 'y' into an integer, and dividing the two integer values, but surely there's a better way of doing this.
>>> a = '4/10'
>>> float(eval(a))
0.4
But I would be careful with eval . It's not safe, you could probably use ast.literal_eval() instead

Multiple int input in same line python [duplicate]

This question already has answers here:
Taking multiple integers on the same line as input from the user in python
(19 answers)
Closed 1 year ago.
I want to take multiple integer inputs in the same line. I know I can take str input and then convert them into integer in the next line but is there any way I can do it in the same line.
I have tried this:
x,y = int(input("->")).split()
print(x,y)
I am getting this error :
ValueError: invalid literal for int() with base 10
You messed up with parenthesis (split works on string not int)
then you expect a tuple for x,y = ...
the solution is:
x, y = [int(i) for i in input("->").split()]
print(x, y)
You are taking int as input which cant be split
x,y = input("->").split()
print(x,y)
you can change to int if you like later
print(int(x),int(y))

Python - create separate lists but integers and strings not working [duplicate]

This question already has answers here:
Negative form of isinstance() in Python
(3 answers)
Closed 2 years ago.
Here's the info:
I have a list like this
trylist=[9,0,-5,1,-600,'Europe','-9',4,'English',0.7,5.9,'0','-2','-3.7','Python']
Looking to create three lists - integer, string and float
Integer list will have: 9,0,-5,1,-600,4
Float list will have: 0.7,5.9
String list will have: Europe,-9,English,0,-2,-3.7,Python
Wrote this program. Output was integers and integers marked as string. Not kind of what I want. Tweaked it to do the same with float. Did not work. Looking for a better way to get the desired output. Thanks!
trylist=[9,0,-5,1,-600,'Europe','-9',4,'English',0.7,5.9,'0','-2','Python']
newlistint=[]
newlistonlyint=[]
print(f'Initial list : {trylist}')
for item in trylist:
try:
int_val = int(item)
print(int_val)
except ValueError:
pass
else:
newlistint.append(item) #will print only integers including numbers mentioned as string and digit of float
print(f'newlistint is : {newlistint}')
newlistonlyint.append(int_val)
print(f'newlistonlyint is :{newlistonlyint}')
trylist = [9,0,-5,1,-600,'Europe','-9',4,'English',0.7,5.9,'0','-2','Python']
int_list = [x for x in trylist if type(x)==int]
float_list = [x for x in trylist if type(x)==float]
str_list = [x for x in trylist if type(x)==str]
You can read about list comprehension here
int() tries to convert its argument to an int, raising a ValueError if this can’t be done. While it’s true that any integer argument to int() will not raise a ValueError, non-integer arguments like ‘9’ can be successfully converted to an integer (the integer 9 in this case), therefore not raising a ValueError.
Hence, trying to verify whether something is an integer by calling int() on it and catching ValueErrors just doesn’t work.
You should really be using the isinstance() function. Specifically, item is an int if and only if isinstance(item, int) returns True. Similarly, you can check for strings or floats by replacing int by str or float.

How can I convert and integer into a string? [duplicate]

This question already has answers here:
How to print list item + integer/string using logging in Python
(2 answers)
Closed 7 years ago.
I am coding in Python, and have reached an error that I cannot seem to solve. Here's the part of the code that it affects.
import random
a = raw_input("Enter text")
b = random.randrange(1,101)
print (a+b)
When I try to run the code, I get the error "TypeError: cannot concatenate 'str' and 'int' objects"
I want to know how to print the result of a+b.
To answer to the question in the title, you can convert an integer into a string with str. But the print function already applies str to its argument, in order to be able to print it.
Here, your problem comes from the fact that a is a string while b is an integer. The + operator works on two strings, or two ints, but not a combination of this two types. If you have two strings, the + will mean concatenate. If you have two ints, the + will mean add. It then depends on the result you want to get.
You can convert a string to an integer by using int.
Try this code:
import random
a = int (raw_input ("Enter int "))
b = random.randrange (1, 101)
print a + b

Converting string to number? [duplicate]

This question already has an answer here:
Turning a list of strings into float
(1 answer)
Closed 9 years ago.
I should get this converted to numbers with float().
How can I do it?
Here is the code I have problems with. It´s simplified to the problem
poly = input().split()
poly.reverse()
return poly
Simply as you said in your question...you can use float:
>>> string = "1234.567"
>>> float(string)
1234.567
You can convert a string to a number in Python with the int(), float() and long() built-in functions.
E.g.
return int(poly)
See the Python docs for details:
int()
float()
long()
If poly is a list of strings you want to convert in floats, do:
floats = [float(s) for s in poly]

Categories

Resources