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']
>>>
Related
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
This question already has answers here:
How do I make a flat list out of a list of lists?
(34 answers)
Closed 7 years ago.
I want to convert multiple lists inside a list? I am doing it with a loop, but each sub list item doesn't get a comma between it.
myList = [['a','b','c','d'],['a','b','c','d']]
myString = ''
for x in myList:
myString += ",".join(x)
print myString
ouput:
a,b,c,da,b,c,d
desired output:
a,b,c,d,a,b,c,d
This can be done using a list comprehension where you will "flatten" your list of lists in to a single list, and then use the "join" method to make your list a string. The ',' portion indicates to separate each part by a comma.
','.join([item for sub_list in myList for item in sub_list])
Note: Please look at my analysis below for what was tested to be the fastest solution on others proposed here
Demo:
myList = [['a','b','c','d'],['a','b','c','d']]
result = ','.join([item for sub_list in myList for item in sub_list])
output of result -> a,b,c,d,a,b,c,d
However, to further explode this in to parts to explain how this works, we can see the following example:
# create a new list called my_new_list
my_new_list = []
# Next we want to iterate over the outer list
for sub_list in myList:
# Now go over each item of the sublist
for item in sub_list:
# append it to our new list
my_new_list.append(item)
So at this point, outputting my_new_list will yield:
['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd']
So, now all we have to do with this is make it a string. This is where the ','.join() comes in to play. We simply make this call:
myString = ','.join(my_new_list)
Outputting that will give us:
a,b,c,d,a,b,c,d
Further Analysis
So, looking at this further, it really piqued my interest. I suspect that in fact the other solutions are possibly faster. Therefore, why not test it!
I took each of the solutions proposed, and ran a timer against them with a much bigger sample set to see what would happen. Running the code yielded the following results in increasing order:
map: 3.8023074030061252
chain: 7.675725881999824
comprehension: 8.73164687899407
So, the clear winner here is in fact the map implementation. If anyone is interested, here is the code used to time the results:
from timeit import Timer
def comprehension(l):
return ','.join([i for sub_list in l for i in sub_list])
def chain(l):
from itertools import chain
return ','.join(chain.from_iterable(l))
def a_map(l):
return ','.join(map(','.join, l))
myList = [[str(i) for i in range(10)] for j in range(10)]
print(Timer(lambda: comprehension(myList)).timeit())
print(Timer(lambda: chain(myList)).timeit())
print(Timer(lambda: a_map(myList)).timeit())
from itertools import chain
myList = [['a','b','c','d'],['a','b','c','d']]
print(','.join(chain.from_iterable(myList)))
a,b,c,d,a,b,c,d
You could also just join at both levels:
>>> ','.join(map(','.join, myList))
'a,b,c,d,a,b,c,d'
It's shorter and significantly faster than the other solutions:
>>> myList = [['a'] * 1000] * 1000
>>> from timeit import timeit
>>> timeit(lambda: ','.join(map(','.join, myList)), number=10)
0.18380278121490046
>>> from itertools import chain
>>> timeit(lambda: ','.join(chain.from_iterable(myList)), number=10)
0.6535200733309843
>>> timeit(lambda: ','.join([item for sub_list in myList for item in sub_list]), number=10)
1.0301431917067738
I also tried [['a'] * 10] * 10, [['a'] * 10] * 100000 and [['a'] * 100000] * 10 and it was always the same picture.
myList = [['a','b','c','d'],[a','b','c','d']]
smyList = myList[0] + myList[1]
str1 = ','.join(str(x) for x in smyList)
print str1
output
a,b,c,d,a,b,c,d
How can I quickly convert a list of dictionaries to a simple list of just the values if the order is not important?
For example:
results = [{'id':'abcd'},
{'id':'bcde'},
{'id':'cdef'}]
to simply
results = ('abcd','bcde','cdef')
You can try this:
>>> results = [{'id':'abcd'},
... {'id':'bcde'},
... {'id':'cdef'}]
>>>
>>> tuple(d['id'] for d in results)
('abcd', 'bcde', 'cdef')
Note that this is not a list but rather a tuple. If you want a list instead:
>>> [d['id'] for d in results]
['abcd', 'bcde', 'cdef']
This should do it:
>>> [val for dic in results for val in dic.values()]
['abcd', 'bcde', 'cdef']
If you want a tuple, just enclose in tuple with parens instead:
>>> tuple(val for dic in results for val in dic.values())
('abcd', 'bcde', 'cdef')
Both of the above work even if dictionaries have more than one value, and regardless of what the keys in the dictionaries are.
This will fit your sample data:
import operator
map(operator.itemgetter('id'), results)
e.g.
results = [{'id':'abcd'},
{'id':'bcde'},
{'id':'cdef'}]
import operator
print map(operator.itemgetter('id'), results)
>>> ['abcd', 'bcde', 'cdef']
BUT, in a general way, you can chain the values of each dictionary in list:
import itertools
print list(itertools.chain(*map(dict.values, results)))
>>> ['abcd', 'bcde', 'cdef']
It sounds like what you essentially want to do is concatenate the values of all the dictionaries into one list. The built-inreduce()function makes translating that into code relatively easy:
reduce(lambda a, b: a+b, (d.values() for d in results))
will give:
['abcd', 'bcde', 'cdef']
You can add an outer call totuple(), if that's what you really want to get:
('abcd', 'bcde', 'cdef')
I was wondering how one can append a portion of a string to a list? Is there an option of both appending based on the position of characters in the string, and another option that is able to take a specific character of interest? For instance, If I had the string "2 aikjhakihaiyhgikjewh", could I not only append the part of the string that was in positions 3-4 but also append the "2" as well? I'm a beginner, so I'm still kinda new to this python thing. Thanks.
You can use slicing to reference a portion of a string like this:
>>> s = 'hello world'
>>> s[2:5]
'llo'
You can append to a list using the append method:
>>> l = [1,2,3,4]
>>> l.append('Potato')
>>> l
[1, 2, 3, 4, 'Potato']
Best way to learn this things in python is to open an interactive shell and start typing commands on it. I suggest ipython as it provides autocomplete which is great for exploring objects methods and properties.
You can append a portion of a string to a list by using the .append function.
List = []
List.append("text")
To append several parts of the string you can do the following:
List = []
String = "2 asdasdasd"
List.append(String[0:2] + String[3:5])
This would add both sections of the string that you wanted.
Use slicing to accomplish what you are looking for:
mystr = "2 aikjhakihaiyhgikjewh"
lst = list(list([item for item in [mystr[0] + mystr[3:5]]])[0])
print lst
This runs as:
>>> mystr = "2 aikjhakihaiyhgikjewh"
>>> lst = list(list([item for item in [mystr[0] + mystr[3:5]]])[0])
>>> print lst
['2', 'i', 'k']
>>>
Slicing works by taking certain parts of an object:
>>> mystr
'2 aikjhakihaiyhgikjewh'
>>> mystr[0]
'2'
>>> mystr[-1]
'h'
>>> mystr[::-1]
'hwejkighyiahikahjkia 2'
>>> mystr[:-5]
'2 aikjhakihaiyhgi'
>>>
You are describing 2 separate operations: slicing a string, and extending a list. Here is how you can put the two together:
In [26]: text = "2 aikjhakihaiyhgikjewh"
In [27]: text[0], text[3:5]
Out[27]: ('2', 'ik')
In [28]: result = []
In [29]: result.extend((text[0], text[3:5]))
In [30]: result
Out[30]: ['2', 'ik']
I am trying to find any permutation of a list inside another Dictionary with tuples.
For example, what would be the best way to find any combination of [1,2,3] inside of a Dictionary which is formatted like this: {(1,3,2):'text',(3,1,2):'text'}.
The only matches that would qualify for [1,2,3] would be (1,2,3),(1,3,2),(2,1,3),(2,3,1),(3,2,1),(3,1,2).
Matches that wouldn't qualify include Lists that don't contain all of the items (For example: (1,2) or (2)), and matches that contain extra items (for example:(1,2,3,4) or (2,3,7,1)).
Use itertools.permutations() to generate all permutations of a list:
from itertools import permutations
if any(tuple(perm) in yourdictionary for perm in permutations(yourlist)):
# match found
but you really want to rethink your data structure. If you made your keys frozenset() objects instead, you simply would test for:
if frozenset(yourlist) in yourdictionary:
# match found
which would be a lot faster.
Demos:
>>> from itertools import permutations
>>> yourdictionary = {(1,3,2):'text',(3,1,2):'text'}
>>> yourlist = [1, 2, 3]
>>> print any(tuple(perm) in yourdictionary for perm in permutations(yourlist))
True
>>> yourdictionary = {frozenset([1, 2, 3]): 'text', frozenset([4, 5, 6]): 'othertext'}
>>> frozenset(yourlist) in yourdictionary
True
>>> frozenset([2, 3]) in yourdictionary
False