I have the following list:
a = ['1', '2', 'hello']
And I want to obtain
a = [1, 2, 'hello']
I mean, convert all integers I can.
This is my function:
def listToInt(l):
casted = []
for e in l:
try:
casted.append(int(e))
except:
casted.append(e)
return casted
But, can I use the map() function or something similar?
Sure you can do this with map
def func(i):
try:
i = int(i)
except:
pass
return i
a = ['1', '2', 'hello']
print(list(map(func, a)))
a = ['1', '2', 'hello']
y = [int(x) if x.isdigit() else x for x in a]
>> [1, 2, 'hello']
>> #tested in Python 3.5
Maybe something like this?
Related
I have seen a variety of answers on here, but none that quite answered my question. I am trying to convert the following list
list = ['A', '2', '8', 'B', '3']
to the following:
list = ['A', 2, 8, 'B', 3]
I want to keep the strings as strings but convert the strings to ints where possible.
I know I could do something like:
list = [int(i) for i in list]
if it were just numbers, but I am unsure how to do it when it is mixed.
There's always try/except:
oldlist = ['A', '2', '8', 'B', '3']
newlist = []
for x in oldlist:
try:
newlist.append(int(x))
except ValueError:
newlist.append(x)
newlist
# ['A', 2, 8, 'B', 3]
You can use str.isdigit():
>>> l = ['A', '2', '8', 'B', '3']
>>> [int(x) if x.isdigit() else x for x in l]
['A', 2, 8, 'B', 3]
Taking negative numbers into account:
>>> l = ['A', '2', '8', 'B', '-3']
>>> [int(x) if x.isdigit() or x.startswith('-') and x[1:].isdigit() else x for x in l]
>>> ['A', 2, 8, 'B', -3]
I would just extract the conversion into a function.
def int_if_possible(value):
try:
return int(value)
except (ValueError, TypeError):
return value
int_list = [int_if_possible(i) for i in int_list]
Also I renamed your list to int_list, so that we can still use the list constructor if required.
You can use try , except block
lst1 = ['A', '2', '8', 'B', '3']
lst2 = []
for i in lst1:
try:
lst2.append(int(i))
except ValueError:
lst2.append(i)
print lst2
Let's say you have:
x = "1,2,13"
and you want to achieve:
list = ["1","2","13"]
Can you do it without the split and replace methods?
What I have tried:
list=[]
for number in x:
if number != ",":
list.append(number)
print(list) # ['1', '2', '1', '3']
but this works only if its a single digit
You could use a regular expression:
>>> import re
>>> re.findall('(\d+)', '123,456')
['123', '456']
Here is a way using that assumes integers using itertools:
>>> import itertools
>>> x = "1,88,22"
>>> ["".join(g) for b,g in itertools.groupby(x,str.isdigit) if b]
['1', '88', '22']
>>>
Here is a method that uses traditional looping:
>>> digit = ""
>>> digit_list = []
>>> for c in x:
... if c.isdigit():
... digit += c
... elif c == ",":
... digit_list.append(digit)
... digit = ""
... else:
... digit_list.append(digit)
...
>>> digit_list
['1', '88', '22']
>>>
In the real world, you'd probably just use regex...
why such construction doesn't work?
l = [1,2,3]
for x in l:
x = str(x)
print(l)
it returnes:
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
instead of expected:
['1', '2', '3']
['1', '2', '3']
['1', '2', '3']
For each iteration you're printing the original list without modifying it.
Use map()
list(map(str, l))
>> ['1', '2', '3']
or a list comprehension
l = [str(x) for x in l]
When you do x = str(x) it changes the value in x to str (and not the element in your list l)
But as you are trying to change the list l
I suggest you try a list comprehension:
l = [str(x) for x in l]
You need to store back the casted x back to the list as below:
l = [1,2,3]
new_l = []
for x in l:
new_l.append(str(x))
print(new_l)
Also,if you're not accustomed with map (see other answers) you could use :
for i,x in enumerate(l):
l[i] = str(x)
But other answers are just better.
I have a list [['4', '9.012'], ['12', '24.305'], ['20', '20.078']] .
Now I want to convert it into its number equivalent
[[4, 9.012], [12, 24.305], [20, 20.078]]
I am new to python.
You can use:
from ast import literal_eval
newlist = [[literal_eval(el) for el in item] for item in mylist]
This way the type will be determined by the type required to hold that number.
If you always have pairs of integer and float,
[[int(x), float(y)] for [x, y] in mylist]
Otherwise, for more generality at the expense of type correctness,
[[float(x) for x in s] for s in mylist]
For more type correctness at the expense of clarity,
def number(x):
try:
return int(x)
except:
return float(x)
[[number(x) for x in s] for s in mylist]
lst = [['4', '9.012'], ['12', '24.305'], ['20', '20.078']]
map(lambda x: [int(x[0]), float(x[1])], lst)
>>> l = [['4', '9.012'], ['12', '24.305'], ['20', '20.078']]
>>> l1 = [ [ float(i[0]), float(i[1]) ] for i in l ]
OR
>>> l
[['4', '9.012'], ['12', '24.305'], ['20', '20.078']]
>>> def f(arg):
... return [float(arg[0]), float(arg[1])]
>>> map(f,l)
[[4.0, 9.012], [12.0, 24.305], [20.0, 20.078]]
I am looking for a different way to get a string list from a tuple of tuples. This is how I do right now:
x = (('a',1), (2,3), (4,), (), (None,))
op_list = []
for item in x:
if item and item[0]:
op_list.append(str(item[0]))
print op_list
Output: ['a', '2', '4']
I cannot think of any other way to get to the list. My question is, is there any better/alternate/pretty way of doing this?
EDIT: Added a few pitfall inputs to the input, like an empty tuple, tuple with None and given the expected output as well. Also edited the question to ensure that I need only a list of strings irrespective of any other data type other than None.
>>> x = (('a',1), (2,3), (4,))
>>> [str(item[0]) for item in x if item and item[0]]
['a', '2', '4']
Maybe using map and lambda functions gives you the easiest and more compact way to do it:
>>> x = (('a',1), (2,3), (4,), (None,), ())
>>> filter(None, map(lambda i: str(i[0]) if len(i) > 0 and i[0] != None else None, x))
['a', '2', '4']
Use itemgetter.
from operator import itemgetter
f = itemgetter(0)
def func(i):
if not i:
return None
r = f(i)
if r:
return str(r)
Using it:
>>> x = (('a',1), (2,3), (4,), None, '', False, [], (None,), ())
>>> filter(None, map(func, x))
['a', '2', '4']
You can make it into a function:
def extract_first_non_none(collection):
return filter(None, map(func, collection))
Or into a class:
class Extractor():
def __init__(self, index):
self.getter = itemgetter(index)
def _func(self, item):
if not item:
return None
r = self.getter(item)
if r != None:
return str(r)
def extract(self, collection):
return filter(None, map(self._func, collection))
Using the class:
>>> x = (('a',1), (2,3), (4,), None, '', False, [], (None,), ())
>>> e = Extractor(0)
>>> e.extract(x)
['a', '2', '4']