How to write a function into a for loop - python

How would one answer this foor loop question using proper python syntax:
def int_all_2(str_list):
'''(list of str) -> NoneType
Replace every str element of str_list with its corresponding
int version.
For example,
>>> sl = ['100', '222', '2', '34']
>>> int_all_2(sl)
>>> sl
[100, 222, 2, 34]
'''
Would it be like this?
l = []
for x in str_list:
l.append (int_all_2(x))
return l

If you want to convert each element of the list to integer and then return a new list you can use map function :
def strs2ints(l):
return map(int,l)
You should also note that function strs2ints doesn't change the contents of array l.
In case you want to change the contents of the original array l, which I do not recommend(you should prefer using "clean" functions over functions with side-effects) you can try the following code :
def strs2ints(l):
for i in range(len(l)):
l[i] = int(l[i])

Assuming your list contains only string representation of numeric integers, you don't even need a function, just list comprehension:
l = [int(itm) for itm in str_list]
If you want to ignore possible strings:
l = [int(itm) for itm in str_list if not itm.isalpha]
Or, if you require a function:
def int_all(str_list):
return [int(itm) for itm in str_list]

Related

convert list to lowercase in python

I have a list in python, which contains alphanumeric elements. I would like to convert all elements to lowercase.
Is it the only way to create a Dataframe using the list and use the lower function?
Here is the example:
l = ['abc123']
l.lower()
Error:
AttributeError: 'list' object has not attribute 'lower'
You have one string element in a list. List doesn't understand string functions. You need to call .lower() on string.
There are several solutions. Use which is best for your use case.
l = ['ABC123']
[s.lower() for s in l] # ['abc123']
list(map(str.lower, l)) # ['abc123']
l[0].lower() # 'abc123'
s, = l # only if l is always 1 element list
s.lower() # 'abc123'
for s in l:
print(s.lower()) # 'abc123'
You can use list comprehension or map function as well.
L = ['ABS123']
l = [i.lower() for i in L]
or
l = list(map(str.lower, L))
gives the same. And could be faster on really big lists.
You can make all of the entries in the list lowercase pretty easily, as shown below.
l = ['abc123']
lower = []
for i in l:
lower.append(i.lower())
l = [char.lower() for char in l ]
print(l)

Why does this function to convert all items in a list to strings not work?

I have a two dimensional array and I try to convert all items within each array to strings.
First I tried to use a function to_str and this approach didn't work. I do not understand why it doesn't work (it returns the input unchanged):
lst = [['test1', 555], ['test2', 3333]]
def to_str(item):
for i in item:
if not isinstance(i, str):
i = str(i)
return item
output = list(map(lambda item:to_str(item), lst))
output: [['test1', 555], ['test2', 3333]]
Then I used a list comprehension instead, and it worked:
output = list(map(lambda item: [str(i) for i in item], lst))
output: [['test1', '555'], ['test2', '3333']]
Why does the first approach using to_str not work?
You're trying to modify the iteration variable named i. This has no effect at all, you're just rewriting the value of a local variable that points to a list element, but not changing the list itself. For this to work you have to modify the list elements at each index position, something like this:
def to_str(item):
# iterate over the indexes in the item
for i in range(len(item)):
# we can remove this check, and simply convert everything to str
if not isinstance(item[i], str):
item[i] = str(item[i])
return item
Or we can create a new list with the results, instead of overwriting the original (but this will be equivalent to using a list comprehension, better use a list comprehension):
def to_str(item):
result = []
for element in item:
# we can remove this check, and simply convert everything to str
if not isinstance(element, str):
result.append(str(element))
else:
result.append(element)
return result
Also, regarding your second approach: it'd be better if you avoid using list, map and lambda, if what you want is to create a new list as a result use a list comprehension directly. This is a more idiomatic way to solve the problem, also removing the unnecessary string check:
[[str(i) for i in item] for item in lst]
=> [['test1', '555'], ['test2', '3333']]
Converted value i is not used anywhere in approach #1 and function just returns input
def to_str(item):
result = []
for i in item:
if not isinstance(i, str):
i = str(i)
result.append(i)
return result

How to change the index of an element in a list/array to another position/index without deleting/changing the original element and its value

For example lets say I have a list as below,
list = ['list4','this1','my3','is2'] or [1,6,'one','six']
So now I want to change the index of each element to match the number or make sense as I see fit (needn't be number) like so, (basically change the index of the element to wherever I want)
list = ['this1','is2','my3','list4'] or ['one',1,'six',6]
how do I do this whether there be numbers or not ?
Please help, Thanks in advance.
If you don't wanna use regex and learn it's mini language use this simpler method:
list1 = ['list4','this1', 'he5re', 'my3','is2']
def mySort(string):
if any(char.isdigit() for char in string): #Check if theres a number in the string
return [float(char) for char in string if char.isdigit()][0] #Return list of numbers, and return the first one (we are expecting only one number in the string)
list1.sort(key = mySort)
print(list1)
Inspired by this answer: https://stackoverflow.com/a/4289557/11101156
For the first one, it is easy:
>>> lst = ['list4','this1','my3','is2']
>>> lst = sorted(lst, key=lambda x:int(x[-1]))
>>> lst
['this1', 'is2', 'my3', 'list4']
But this assumes each item is string, and the last character of each item is numeric. Also it works as long as the numeric parts in each item is single digit. Otherwise it breaks. For the second one, you need to define "how you see it fit", in order to sort it in a logic.
If there are multiple numeric characters:
>>> import re
>>> lst = ['lis22t4','th2is21','my3','is2']
>>> sorted(lst, key=lambda x:int(re.search(r'\d+$', x).group(0)))
['is2', 'my3', 'list4', 'this21']
# or,
>>> ['is2', 'my3', 'lis22t4', 'th2is21']
But you can always do:
>>> lst = [1,6,'one','six']
>>> lst = [lst[2], lst[0], lst[3], lst[1]]
>>> lst
['one', 1, 'six', 6]
Also, don't use python built-ins as variable names. list is a bad variable name.
If you just want to move element in position 'y' to position 'x' of a list, you can try this one-liner, using pop and insert:
lst.insert(x, lst.pop(y))
If you know the order how you want to change indexes you can write simple code:
old_list= ['list4','this1','my3','is2']
order = [1, 3, 2, 0]
new_list = [old_list[idx] for idx in order]
If you can write your logic as a function, you can use sorted() and pass your function name as a key:
old_list= ['list4','this1','my3','is2']
def extract_number(string):
digits = ''.join([c for c in string if c.isdigit()])
return int(digits)
new_list = sorted(old_list, key = extract_number)
This case list is sorted by number, which is constructed by combining digits found in a string.
a = [1,2,3,4]
def rep(s, l, ab):
id = l.index(s)
q = s
del(l[id])
l.insert(ab, q)
return l
l = rep(a[0], a, 2)
print(l)
Hope you like this
Its much simpler

A function that takes two arguments- a function f and a list l and applies the function over the elements of the list and returns them as a list

I made a function:
def remove_trailing_newlines(s):
s_clean = s.rstrip()
return s_clean
This function will remove the trailing \n at end of string s.
Now I want to apply the same to every element (which is string) of a list.
I want to create a function mapl(f, l) where f is remove_trailing_newlines() and l is a list on which we have to apply f and return it as a list
For example:
on the list l = ['Apple\n','banana\n','mango\n']
I want the output as : l = ['Apple','banana','mango']
using the mapl(f,l) function
You are looking for:
list(map(remove_trailing_newlines, l))
We can pass custom function and apply the function to each element of the list.
You can also directly call rstrip inside map as in #yatu's answer.
I think you want to make a function like a builtin map function by yourself. Try the following:
def remove_trailing_newlines(s):
s_clean = s.rstrip()
return s_clean
def mapl(f,l):
ret = []
for i in l:
ret.append(f(i))
return ret
l = ['Apple\n','banana\n','mango\n']
new_list = mapl(remove_trailing_newlines,l)
print(new_list)
>> ['Apple', 'banana', 'mango']
Let me know if it does not fulfill your requirement

How to remove a string within a list item in python

On a project I am currently getting returned a list as follows:
[u'40620', u'00700', u'24150', u'11700']
How can I edit the list so it is returned just integer values:
[40620, 00700, 24150, 11700]
Thanks!
Use a list comprehension and int:
>>> lst = [u'40620', u'00700', u'24150', u'11700']
>>> [int(x) for x in lst]
[40620, 700, 24150, 11700]
>>>
Simple one liner:
results = map(int, results)

Categories

Resources