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)
Related
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
I have a list of lists like this:
[["testo=text1","testo2=text2"],["testo3=text3","testo4=text4"]]
I want to split each element of each sublist by "=".
Desired result:
[['testo', 'text1'],['testo2', 'text2']]
My attempt was to iterate over each sub-list and split. But it's not working:
[j.split("=") for j in [i for i in splitted_params]]
keep getting 'list' object has no attribute 'split' error
try:
l = [["testo=text1","testo2=text2"],["testo3=text3","testo4=text4"]]
new_l = [inner_element.split("=") for x in l for inner_element in x]
print(new_l)
output:
[['testo', 'text1'], ['testo2', 'text2'], ['testo3', 'text3'], ['testo4', 'text4']]
You shouldn't try to be clever with python list comprehensions. In my opinion, you should go for the readable solution. :)
if __name__ == '__main__':
data = [
["testo=text1","testo2=text2"],
["testo3=text3","testo4=text4"]
]
for arr in data:
for index in range( len(arr) ):
arr[index] = arr[index].split('=')
print(data)
In your expression, [j.split("=") for j in [i for i in splitted_params]], the inner expression, [i for i in splitted_params] is evaluated first, which gives you a list. You did nothing in this list comprehension. Then, when you evaluate [j.split("=") for j in SOME_RESULT_YOU_GOT], you are trying to split a list, which is not possible.
You can use chain.from_iterable() to avoid the double for loop in the list comprehension:
from itertools import chain
l = [["testo=text1", "testo2=text2"], ["testo3=text3", "testo4=text4"]]
[i.split('=') for i in chain.from_iterable(l)]
# [['testo', 'text1'], ['testo2', 'text2'], ['testo3', 'text3'], ['testo4', 'text4']]
Explanation why your solution doesnât work:
splitted_params = [["testo=text1", "testo2=text2"], ["testo3=text3", "testo4=text4"]]
print([i for i in splitted_params] == splitted_params)
# True
So when you use [i for i in splitted_params] inside your listcomp you get the same list.
I think the problem is that [i for i in splitted_params] this doesn't return the lists in your list of lists.
it just returns your list of lists so when you then loop through it again, it will try to split the lists in the list of lists.
so I would suggest you just do a loop in a loop like this
listoflists = [["testo=text1", "testo2=text2"], ["testo3=text3", "testo4=text4"]]
for i in listoflists:
for j in i:
print(j.split("="))
It may not be as pretty but it does get the job done.
I want to check if strings in a list of strings contain a certain substring. If they do I want to save that list item to a new list:
list = ["Maurice is smart","Maurice is dumb","pie","carrots"]
I have tried using the following code:
new_list = [s for s in list if 'Maurice' in list]
but this just replicates the list if one of its items is 'Maurice'.
So I was wondering if, maybe, there was a way to solve this by using the following syntax:
if "Maurice" in list:
# Code that saves all list items containing the substring "Maurice" to a new list
Result should then be:
new_list = ["Maurice is smart", "Maurice is dumb"]
If been looking for a way to do this but I can not find anything.
You could do this:
list = ["Maurice is smart","Maurice is dumb","pie","carrots"]
new_list = [x for x in list if "Maurice" in x]
print(new_list)
Output:
['Maurice is smart', 'Maurice is dumb']
You could use Python's builtin filter:
data = ["Maurice is smart", "Maurice is dumb", "pie", "carrots"]
res = filter(lambda s: 'Maurice' in s, data)
print(res)
Output:
['Maurice is smart', 'Maurice is dumb']
The first argument is a predicate function (a simple lambda here) which must evaluate to True for the element of the iterable to be considered as a match.
filter is useful whenever an iterable must be filtered based on a predicate.
Also, a little extra, imagine now this data to be filtered:
data = ["Maurice is smart","Maurice is dumb","pie","carrots", "maurice in bikini"]
res = filter(lambda s: 'maurice' in s.lower(), list)
print(res)
Ouput:
['Maurice is smart', 'Maurice is dumb', 'maurice in bikini']
You can use a list comprehension.
Also, make sure not to use the built in list as variable name.
my_list = ["Maurice is smart", "Maurice is dumb", "pie", "carrots"]
[e for e in my_list if 'Maurice' in e]
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]
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)