Converting string list to number equivalent - python

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

Related

sort my python list based on multiple values

I want to sort lists as the following:
input:
mylist = [['12','25'],['4','7'],['12','14']]
output:
[['4','7'],['12','14'],['12','25']]
the current code that I use only sorts the first number of the lists:
def defe(e):
return int(e[0])
mylist = [['12','25'],['4','7'],['12','14']]
mylist.sort(key=defe)
print(mylist)
output:
[['4','7'],['12','25'],['12','14']]
Try:
sorted(mylist, key=lambda x: (int(x[0]), int(x[1])))
Output:
[['4', '7'], ['12', '14'], ['12', '25']]
If sublists are longer than 2, then
sorted(mylist, key=lambda x: list(map(int, x)))
is better.

Map if it can be converted

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?

Int convert to str using for cycle

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.

Python: Maximum of lists of 2 or more elements in a tuple using key

Lets say i have a tuple of list like:
g = (['20', '10'], ['10', '74'])
I want the max of two based on the first value in each list like
max(g, key = ???the g[0] of each list.something that im clueless what to provide)
And answer is ['20', '10']
Is that possible? what should be the key here?
According to above answer.
Another eg:
g = (['42', '50'], ['30', '4'])
ans: max(g, key=??) = ['42', '50']
PS: By max I mean numerical maximum.
Just pass in a callable that gets the first element of each item. Using operator.itemgetter() is easiest:
from operator import itemgetter
max(g, key=itemgetter(0))
but if you have to test against integer values instead of lexographically sorted items, a lambda might be better:
max(g, key=lambda k: int(k[0]))
Which one you need depends on what you expect the maximum to be for strings containing digits of differing length. Is '4' smaller or larger than '30'?
Demo:
>>> g = (['42', '50'], ['30', '4'])
>>> from operator import itemgetter
>>> max(g, key=itemgetter(0))
['42', '50']
>>> g = (['20', '10'], ['10', '74'])
>>> max(g, key=itemgetter(0))
['20', '10']
or showing the difference between itemgetter() and a lambda with int():
>>> max((['30', '10'], ['4', '10']), key=lambda k: int(k[0]))
['30', '10']
>>> max((['30', '10'], ['4', '10']), key=itemgetter(0))
['4', '10']
You can use lambda to specify which item should be used for comparison:
>>> g = (['20', '10'], ['10', '74'])
>>> max(g, key = lambda x:int(x[0])) #use int() for conversion
['20', '10']
>>> g = (['42', '50'], ['30', '4'])
>>> max(g, key = lambda x:int(x[0]))
['42', '50']
You can also use operator.itemegtter, but in this case it'll not work as the items are in string form.
If by 'max' you mean lexicographic max:
>>> max(['0','5','10','100'])
'5'
>>> min(['0','5','10','100'])
'0'
Then you can just use max with no key function at all:
>>> max((['20', '10'], ['10', '74']))
['20', '10']
>>> max((['42', '50'], ['30', '4']))
['42', '50']
If you mean numerical max, use a lambda:
>>> max((['0','10'],['5','100'],['100','1000']))
['5', '100']
>>> max((['0','10'],['5','100'],['100','1000']),key=lambda l:int(l[0]))
['100', '1000']
If you store numbers as numbers:
g = ([20, 10], [10, 74])
max(g)

Removing elements from a list containing specific characters [duplicate]

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 1 year ago.
I want to remove all elements in a list which contains (or does not contain) a set of specific characters, however I'm running in to problems iterating over the list and removing elements as I go along. Two pretty much equal examples of this is given below. As you can see, if two elements which should be removed are directly following each other, the second one does not get removed.
Im sure there are a very easy way to do this in python, so if anyone know it, please help me out - I am currently making a copy of the entire list and iterating over one, and removing elements in the other...Not a good solution I assume
>>> l
['1', '32', '523', '336']
>>> for t in l:
... for c in t:
... if c == '2':
... l.remove(t)
... break
...
>>> l
['1', '523', '336']
>>> l = ['1','32','523','336','13525']
>>> for w in l:
... if '2' in w: l.remove(w)
...
>>> l
['1', '523', '336']
Figured it out:
>>> l = ['1','32','523','336','13525']
>>> [x for x in l if not '2' in x]
['1', '336']
Would still like to know if there is any way to set the iteration back one set when using for x in l though.
List comprehensions:
l = ['1', '32', '523', '336']
[ x for x in l if "2" not in x ]
# Returns: ['1', '336']
[ x for x in l if "2" in x ]
# Returns: ['32', '523']
l = ['1', '32', '523', '336']
stringVal = "2"
print(f"{[ x for x in l if stringVal not in x ]}")
# Returns: ['1', '336']
print(f"{[ x for x in l if stringVal in x ]}")
# Returns: ['32', '523']
If I understand you correctly,
Example:
l = ['1', '32', '523', '336']
[x for x in l if "2" not in x]
# Returns: ['1', '336']
fString Example:
l = ['1', '32', '523', '336']
stringVal = "2"
print(f"{[x for x in l if stringVal not in x]}")
# Returns: ['1', '336']
might do the job.
In addition to #Matth, if you want to combine multiple statements you can write:
l = ['1', '32', '523', '336']
[ x for x in l if "2" not in x and "3" not in x]
# Returns: ['1']
fString Example
l = ['1', '32', '523', '336']
stringValA = "2"
stringValB = "3"
print(f"{[ x for x in l if stringValA not in x and stringValB not in x ]}")
# Returns: ['1']
Problem you could have is that you are trying to modify the sequence l same time as you loop over it in for t loop.

Categories

Resources