Int convert to str using for cycle - python

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.

Related

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?

Changing lists inside a list to strings inside a list

How do I return my list so that the list is composed of strings rather than lists?
Here is my attempt:
def recipe(listofingredients):
listofingredients = listofingredients
newlist = []
newlist2 = []
for i in listofingredients:
listofingredients = i.strip("\n")
newlist.append(listofingredients)
for i in newlist:
newlist = i.split()
newlist2.append(newlist)
return newlist2
result = recipe(['12345\n','eggs 4\n','$0.50\n','flour 5\n','$2.00\n'])
print result
And my output is this:
[['12345'], ['eggs', '4'], ['$0.50'], ['flour', '5'], ['$2.00']]
Desired output:
['12345', 'eggs', '4', '$0.50', 'flour', '5', '$2.00']
I know that my issue here is appending one list to another, but I'm not sure how to use .strip() and .split() on anything other than a list.
Use extend and split:
>>> L = ['12345\n','eggs 4\n','$0.50\n','flour 5\n','$2.00\n']
>>> res = []
>>> for entry in L:
res.extend(entry.split())
>>> res
['12345', 'eggs', '4', '$0.50', 'flour', '5', '$2.00']
split splits at white spaces per default. Strings with a new line a the end and no space inside are turned into a one-element list:
>>>'12345\n'.split()
['12345']
Strings with a space inside split into a two-element list:
>>> 'eggs 4\n'.split()
['eggs', '4']
The method extend() helps to build a list from other lists:
>>> L = []
>>> L.extend([1, 2, 3])
>>> L
[1, 2, 3]
>>> L.extend([4, 5, 6])
L
[1, 2, 3, 4, 5, 6]
You can use Python's way of doing this. Take the advantage of list comprehension and strip() method.
recipes = ['12345\n','eggs 4\n','$0.50\n','flour 5\n','$2.00\n']
recipes = [recipe.split() for recipe in recipes]
print sum(recipes, [])
Now the result will be
['12345', 'eggs', '4', '$0.50', 'flour', '5', '$2.00']
For further reading
https://stackoverflow.com/a/716482/968442
https://stackoverflow.com/a/716489/968442

Converting string list to number equivalent

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

How can i sort the list with keys in python

I have the two list dictionary like this
obj1 = [mydict['obj1'],mydict['obj2'],mydict['obj3'],mydict['obj4']]
obj2 = [mydict['obj1'],mydict['obj2'],mydict['obj3'],mydict['obj4'], mydict['obj5'] ]
Now i want that
Count the number of elements in each list
Then based on whichever is greater then get that list of objects
I want a single list which conatins the above two list of(list of) dictionaries based on the higher number of elements so that i cause something like this
mylist = myfunc(objects1, objects2 )
mylist should be a list like [objects1, objects2] depending upon who has greater number of objects.
what is the best way to do that with less lines of code
Something like EDIT
mylist = sorted([obj1, obj2], key=lambda a: len(a), reverse=True)
There's no need to use a lambda function if it's just going to call a function anyway.
>>> objects1 = [1, 2, 3]
>>> objects2 = ['1', '2', '3', '4']
>>>
>>> mylist = [objects1, objects2]
>>> max(mylist, key=len)
['1', '2', '3', '4']
>>> sorted(mylist, key=len, reverse=True)
[['1', '2', '3', '4'], [1, 2, 3]]
objects1 = [1, 2, 3]
objects2 = ['1', '2', '3', '4']
mylist = [objects1, objects2]
mylist.sort(key=len, reverse=True)
print mylist
[['1', '2', '3', '4'], [1, 2, 3]]

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