Converting Strings to int in List [duplicate] - python

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)

Related

How can i convert user enter number into list in python? Like user entered 56989 and i want these number separately in list{5,6,9,8,9}

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 /

Decimal with exponential

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)

Python issue with list and join function

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

why sort in python is not working?

code:
list=['1','85863','432','93','549834']
list.sort()
print (list)
Actual output:
>>>
['1', '432', '549834', '85863', '93']
#why sort is not working
Expected output:
['1','93','432','83863','549834']
I have tried other sort operations also but they are displaying same output.
when i tried to read list from keyboard input they are reading only strings but not int please help me why?
when i tried to read list from keyboard input they are reading only strings but not int please help me why
if x is a string, just use int(x) to convert to int
You're sorting strings (text), not by numerical values like integers
For your expected output you have to convert to ints first
my_list= ['1','85863','432','93','549834']
my_list = [int(x) for x in my_list]
Now you can sort numerically, and get a list of ints
my_list.sort()
N.B. avoid using list as variable name, it is a Python built-in
I presume you want to sort by the sum to match your expected output:
l = ['1','85863','432','93','549834']
l.sort(key=lambda x: sum(map(int,x)))
print(l)
['1', '432', '93', '83863', '549834']
You need to first convert the strings to int.
list = [int(ele) for ele in list]
list.sort()
print list
Without int:
lst = ['1','85863','432','93','549834']
lst.sort()
lst.sort(key=len)
print(lst)
This give:
['1', '93', '432', '85863', '549834']
And if you want integers…
my_int = int(input())
I simply missed the logic of converting a string into int.By default python input will be taken as a string. so,we can use any method mentioned in the answers to convert in to string and then sort() method works succesufully over int

How to convert strings to ints in a nested list? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to convert strings into integers in python?
listy = [['1', '2', '3', '4', '5'], "abc"]
for item in listy[0]:
int(item)
print listy
In a nested list, how can I change all those strings to ints? What's above gives me an output of:
[['1', '2', '3', '4', '5'], 'abc']
Why is that?
Thanks in advance!
You need to assign the converted items back to the sub-list (listy[0]):
listy[0][:] = [int(x) for x in listy[0]]
Explanation:
for item in listy[0]:
int(item)
The above iterates over the items in the sub-list and converts them to integers, but it does not assign the result of the expression int(item) to anything. Therefore the result is lost.
[int(x) for x in listy[0]] is a list comprehension (kind of shorthand for your for loop) that iterates over the list, converting each item to an integer and returning a new list. The new list is then assigned back (in place, optional) to the outer list.
This is a very custom solution for your specific question. A more general solution involves recursion to get at the sub-lists, and some way of detecting the candidates for numeric conversion.

Categories