I have a list like this:
a = ['4.2332e-9']
I think the number is a string here and I need it as a number. If I try:
a1 = float(a)
I get an error:
float() argument must be a string or a number.
If I try:
a1 = Decimal(a)
I also get an error:
Invalid tuple size in creation of Decimal from list or tuple. The list or tuple should have exactly three elements.
Any ideas of how I can solve it?
lst = ['4.2332e-9', '-8', '5.7', '6.423', '-5', '-6.77', '10']
print map(float, lst)
Related
This question already has answers here:
Convert all strings in a list to int
(10 answers)
Closed last month.
have a list with numeric strings, like so:
numbers = ['1', '5', '10', '8'];
I would like to convert every list element to integer, so it would look like this:
numbers = [1, 5, 10, 8];
The natural Python way of doing this is using list comprehensions:
intlist = [int(element) for element in stringlist]
This syntax is peculiar to the Python language and is a way to perform a "map" with an optional filtering step for all elements of a sequnce.
An alterantive way, which will be more familiar for programmers that know other languages is to use the map built-in: in it, a function is passed as the first parameter, and the sequence to be processed as the second parameter. The object returned by map is an iterator, that will only perform the calculations on each item as it is requested. If you want an output list, you should build a list out of the object returned by map:
numbers = list(map(int, stringlist))
You can use a simple function called map:
numbers = ['1', '5', '10', '8']
numbers = list(map(int, numbers))
print(numbers)
This will map the function int to each element in the iterable. Note that the first argument the map is a function.
you can use generator objects
[int(i) for i in numbers]
Sometimes int() gives convertion error if the input it's not a valid variable. In that case must create a code that wraps all convertion error.
numbers = []
not_converted = []
for element in string_numbers:
try:
number = int(element)
if isinstance(number, int):
numbers.append(number)
else:
not_converted.append(element)
except:
not_converted.append(element)
If you expect that the input it's aways a string int you can simply convert like:
numbers = [int(element) for element in string_numbers]
You can use the below example:-
numbers = ['3', '5', '7', '9']
numbers = list(map(int, numbers))
print(numbers)
I have a list of float numbers (appear as strings) and NaN values.
import numpy as np
mylist = ['1.0', '0.0', np.nan, 'a']
I need to convert float string values into integer string values, while ignoring the rest of records:
mylist = ['1', '0', np.nan, 'a']
How can I do it?
I wrote the following code, but I don't know how to handle the exceptions np.nan, a, etc.
mylist2 = []
for i in mylist:
mylist2.append(str(int(float(n))))
You can use a map that calls a function to convert them to ints:
def to_int(x):
try:
x = str(int(float(x)))
except:
pass
return x
np.array(list(map(to_int, mylist)), dtype=object)
# array(['1', '0', nan, 'a'], dtype=object)```
Although there are different ways to achieve this. but let's go your way.
This might help.
mylist2 = []
for i in mylist:
try:
mylist2.append(str(int(float(n))))
except:
pass
Assuming you want to just use the original values when they are not numeric strings that can be converted to integers, you can write a helper function to try doing the conversion, and return the original value if an exception is raised.
def try_int(s):
try:
return str(int(float(s)))
except:
return s
mylist2 = [try_int(s) for s in mylist]
Be aware that the conversion from a float string to an int can sometimes make the strings much longer; for example, the string '9e200' will be converted to an integer string with 201 digits.
Because i wanna make a program for reverse of number entered by user .So after getting number into list,will do indexing to get reversal of that number entered by user.If Yes so How??or No so what is the other method.
#reverse of a number
num = int(input("Enter a number"))
list = [num]
print(list)
list[3]
print(list)
Assuming the user entered "12345", doing
my_list = list(input("Enter a number"))
Would give you a list ['1', '2', '3', '4', '5'] (of strings)
If you just want to reverse it and print it, there are several ways. To reverse it we can my_list = my_list[::-1] for example. The more readable way we can use to reverse it "in-place":
my_list.reverse()
Either way, we now have a list that is ['5', '4', '3', '2', '1']
You can just print that, but I assume you want to turn it back into a string, we can do that with
my_str = ''.join(my_list)
Putting it all together:
my_list = list(input("Enter a number"))
my_list.reverse()
my_str = ''.join(my_list)
print(my_str)
Would print the reverse of anything the user entered (doesn't have to be numbers, there's a whole other verification we need for that). As was mentioned by #FraggaMuffin in a comment, this can all be done in one line (by using the built-in reversed function, avoiding the list altogether):
print(''.join(reversed(input("Enter a number"))))
Notice however the most important thing, we didn't use the word list as a variable, because that would destroy the built-in list, that's why it's called my_list in my example, same with str and my_str
I hope this helps you
use list() amd map() function. use a[::-1] to reverse the list.
a =list(map(int,input()))
print(a)
print(a[::-1])
print(a[2])
Input:
56989
Output:
[5,6,9,8,9] /normal list /
[9,8,9,6,5] /reversed list /
9 /accesing the reversed list /
How do I append two digit integer into a list using for loop without splitting them. For example I give the computer 10,14,13,15 and I get something like 1,0,1,4,1,3,1,5. I tried to go around this, but I ended up with a new issue, which is Type Error: sequence item 0: expected string, int found
def GetNumbers(List):
q=[]
Numberlist = []
for i in List:
if i.isdigit():
q.append(int(i))
else:
Numberlist.append(''.join(q[:]))
del q[:]
return Numberlist
Ideal way will be to use str.split() function as:
>>> my_num_string = "10,14,13,15"
>>> my_num_string.split(',')
['10', '14', '13', '15']
But, since you mentioned you can not use split(), you may use regex expression to extract numbers from string as:
>>> import re
>>> re.findall('\d+', my_num_string)
['10', '14', '13', '15']
Else, if you do not want to go with any fancy method, you may achieve it with simple for loop as:
num_str, num_list = '', []
# ^ Needed for storing the state of number while iterating over
# the string character by character
for c in my_num_string:
if c.isdigit():
num_str += c
else:
num_list.append(num_str)
num_str = ''
The numbers in num_list will be in the form of str. In order to convert them to int, you may explicitly convert them as:
num_list = [int(i) for i in num_list] # OR, list(map(int, num_list))
I am trying to create a function and I keep on getting the same error message. And this is something that I have had a problem with for a while. The (key) input is supposed to be an integer. The same integer that's (x). Like input 200 for key/x and the output would be '11001000'. The error message I keep getting is:
"TypeError: 'int' object is not iterable"
I am trying to make it so that all of the numbers are integers. I am trying to make a function that executes the same thing that "{0:b}".format(200) would deliver. So the code that I have come up with is:
def createBinKeyFromKey(key):
for x in key:
return "{o:b}".format(x)
I have also tried to use while loop to execute it correctly and not get an error message, but that hasn't worked so far.
I would like to call an integer. As in the place where it says (key), the input there would be an integer. And then it would return the binary string of the integer. For example I would input createBinKeyFromKey(200) in python shell and it would return '11001000'
You can't iterate over an integer, to get a range of numbers use range() or xrange().
range() creates a whole list first, while xrange() returns an iterator(memory efficient)
here:
def createBinKeyFromKey(key):
for x in range(key):
yield "{0:b}".format(x) #use yield as return will end the loop after first iteration
Using yield makes it a generator function.
demo:
>>> list(createBinKeyFromKey(10))
['0', '1', '10', '11', '100', '101', '110', '111', '1000', '1001']
>>> for x in createBinKeyFromKey(5):
... print x
0
1
10
11
100
help on range:
>>> range?
range(stop) -> list of integers
range(start, stop[, step]) -> list of integers
Return a list containing an arithmetic progression of integers.
range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
When step is given, it specifies the increment (or decrement).
For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!
These are exactly the valid indices for a list of 4 elements.