So i have a question, how can i sort this list:
['Pera','mela','arancia','UVA']
to be like this:
['arancia','mela','Pera','UVA']
In the exercise it said to use the sorted() function with the cmp argument.
You can easily do that, using the key argument:
my_list = ['Pera','mela','arancia','UVA']
my_list.sort(key=str.lower)
Which will get your lowercases chars first.
This will change the object in-place and my_list will be sorted.
You can use sorted function with the same key argument as well, if you want to have a new list. For example:
my_list = ['Pera','mela','arancia','UVA']
my_sorted_list = sorted(my_list,key=str.lower)
Output will be:
>>> my_list
['Pera','mela','arancia','UVA']
>>> my_sorted_list
['arancia', 'mela', 'Pera', 'UVA']
You need to sort your elements based lowercase representation of the strings:
sorted(['Pera','mela','arancia','UVA'], key=str.lower)
this will output:
['arancia', 'mela', 'Pera', 'UVA']
Use sorted() with a key.
>>> mc = ['Pera','mela','arancia','UVA']
>>> sorted(mc, key=str.lower)
['arancia', 'mela', 'Pera', 'UVA']
This will help you:
>>> words = ['Pera','mela','arancia','UVA']
>>> sorted(words)
['Pera', 'UVA', 'arancia', 'mela']
>>> sorted(words, key=str.swapcase)
['arancia', 'mela', 'Pera', 'UVA']
Hope this helps
Related
I have a list as below:
mylist = ['L11_1','E12_3','F7_3']
What I want to do is to create a string based on the items of mylist as below:
mystring = df['L11_1']+df['E12_3']+df['F7_3']
What I have tried is not straightforward:
for i in mylist:
mystring='df['+"'"+i+"'"+']+'
print(mystring,end='')
I tried to use the join() but was not sure how to define df[] with it. Any suggestions? Thank you.
Is this what you're looking for? You can define the df using f-strings.
mystring = "+".join([f"df['{x}']" for x in mylist])
print(mystring)
>>> df['L11_1']+df['E12_3']+df['F7_3']
mylist = ['L11_1','E12_3','F7_3']
string = "+".join([f"df['{i}']" for i in mylist])
output:
"df['L11_1']+df['E12_3']+df['F7_3']"
I have several strings like this:
mylist = ['pearsapple','grapevinesapple','sinkandapple'...]
I want to parse the parts before apple and then append to a new list:
new = ['pears','grapevines','sinkand']
Is there a way other than finding starting points of 'apple' in each string and then appending before the starting point?
By using slicing in combination with the index method of strings.
>>> [x[:x.index('apple')] for x in mylist]
['pears', 'grapevines', 'sinkand']
You could also use a regular expression
>>> import re
>>> [re.match('(.*?)apple', x).group(1) for x in mylist]
['pears', 'grapevines', 'sinkand']
I don't see why though.
I hope the word apple will be fix (fixed length word), then we can use:
second_list = [item[:-5] for item in mylist]
If some elements in the list don't contain 'apple' at the end of the string, this regex leaves the string untouched:
>>> import re
>>> mylist = ['pearsapple','grapevinesapple','sinkandapple', 'test', 'grappled']
>>> [re.sub('apple$', '', word) for word in mylist]
['pears', 'grapevines', 'sinkand', 'test', 'grappled']
By also using string split and list comprehension
new = [x.split('apple')[0] for x in mylist]
['pears', 'grapevines', 'sinkand']
One way to do it would be to iterate through every string in the list and then use the split() string function.
for word in mylist:
word = word.split("apple")[0]
String
string1 = '"{ABCD-1234-3E3F},MEANING1","{ABCD-1B34-3X5F},MEANING2","{XLMN-2345-KFDE},WHITE"'
Expected Result
dict1 = {'{ABCD-1234-3E3F}' : 'MEANING1', '{ABCD-1B34-3X5F}' : 'MEANING2', '{XLMN-2345-KFDE}' : 'WHITE'}
Perhaps it is simple question,
Is there any easy method to split string1 to dict1?
If you are looking for a one-liner, this will work:
>>> dict(tuple(x.split(',')) for x in string1[1:-1].split('","'))
{'{ABCD-1B34-3X5F}': 'MEANING2', '{XLMN-2345-KFDE}': 'WHITE', '{ABCD-1234-3E3F}': 'MEANING1'}
string1 = '"{ABCD-1234-3E3F},MEANING1","{ABCD-1B34-3X5F},MEANING2","{XLMN-2345-KFDE},WHITE"'
elements = string1.replace('"','').split(',')
dict(zip(elements[::2],elements[1::2]))
You can first split the original string and extract elements from it. Now you can pair element in odd and even positions and turn them into a dict.
And here another one-liner alternative:
>>> string1 = '"{ABCD-1234-3E3F},MEANING1","{ABCD-1B34-3X5F},MEANING2","{XLMN-2345-KFDE},WHITE"'
>>> dict((nm, v) for nm,v in [pair.split(',') for pair in eval(string1)])
>>> {'{ABCD-1234-3E3F}': 'MEANING1', '{ABCD-1B34-3X5F}': 'MEANING2', '{XLMN-2345-KFDE}': 'WHITE'}
Given a list of lists like this :
[["fileA",7],["fileB",4],["fileC",17],["fileD",15]]
How would you return the first element associated to the smallest value ? In this instance "fileB" since it has the smallest value (4). I'm guessing the shortest way would be using list comprehension .
Actually, a list comprehension wouldn't be the best tool for this. Instead, you should use min, its key function, and operator.itemgetter:
>>> from operator import itemgetter
>>> lst = [["fileA",7],["fileB",4],["fileC",17],["fileD",15]]
>>> min(lst, key=itemgetter(1))
['fileB', 4]
>>> min(lst, key=itemgetter(1))[0]
'fileB'
>>>
Without importing anything you can do:
min(lst, key = lambda x: x[1])[0]
I came up with this weird idea which doesn't use anything but simple generator expression:
min((x[1], x[0]) for x in lst)[1]
It is based on the fact that the minimization is done on the first element of a tuple/list by default.
You should probably just convert the data to a dictionary, since that immediately seems a lot more sensible than having a list of lists. Then you can manipulate and access your data more easily.
myLists = [["fileA",7],["fileB",4],["fileC",17],["fileD",15]]
myDict = dict(myLists)
min(myDict, key=myDict.get)
# 'fileB'
I have got a list i.e.
ls= [u'Cancer',u"Men's",u'Orthopedics',u'Pediatric',u"Senior's",u"Women's"]
ls.sort() does not seem to work here due to presence of single quote in the list elements.
I need to sort this list. Any idea???
Actually, the question is valid and the answer is not exactly correct in general case.
If the test material was not already sorted, it would not get correctly alphabetized but the 's would cause the list to be sorted to wrong order:
>>> l = ["'''b", "a", "a'ab", "aaa"]
>>> l.sort()
>>> l
["'''b", 'a', "a'ab", 'aaa']
>>> from functools import partial
>>> import string
>>> keyfunc = partial(string.replace, old="'", new="")
>>> l.sort(key=keyfunc)
>>> l
['a', 'aaa', "a'ab", "'''b"]
>>> ls
[u'Cancer', u"Men's", u'Orthopedics', u'Pediatric', u"Senior's", u"Women's"]
>>> ls.sort()
>>> ls
[u'Cancer', u"Men's", u'Orthopedics', u'Pediatric', u"Senior's", u"Women's"]
Since the list was sorted in the first place, it didn't change. sort has no problem with ' - but note that it sorts before the a-z and A-Z characters:
>>> ls
[u'abc', u'abz', u"ab'"]
>>> ls.sort()
>>> ls
[u"ab'", u'abc', u'abz']
>>>