I'm looking for the most efficient way to add an element to a comma-separated string while maintaining alphabetical order for the words:
string = 'Apples, Bananas, Grapes, Oranges' addition = 'Cherries' result = 'Apples, Bananas, Cherries, Grapes, Oranges'
Also, a way to do this but while maintaining IDs:
string = '1:Apples, 4:Bananas, 6:Grapes, 23:Oranges' addition = '62:Cherries' result = '1:Apples, 4:Bananas, 62:Cherries, 6:Grapes, 23:Oranges'
Sample code is greatly appreciated. Thank you so much.
For the first case:
alist = string.split(', ') result = ', '.join(sorted(alist + [addition]))
For the second case:
alist = string.split(', ') result = ', '.join(sorted(alist + [addition], key=lambda s: s.split(':', 1)))
If you have many thousands of items in the list, the first case might show measurable performance improvement if you're willing to go to the much-greater complication of bisect.insort; but that doesn't support a
key=, so the extra complication in the second case would be staggering and probably not even buy you any performance.
The kind of optimizations mentioned in the last paragraphs are worth considering only if a profile of your whole application shows that this operation is a crucial bottleneck for it (and if it is, you'd gain much more speed by keeping this data structure as a list of words,
', '-joining it only at need presumably for output purposes, rather than splitting up and rejoining thousands and thousands of times for the kind of extremely long lists where such optimizations might possibly be warranted).