I want to sort a given array of strings alphabetically using python, but lowercase words should appear first.
An example:
#!/usr/local/bin/python2.7
arr=['A','e','a','D','f','B']
arr.sort()
for s in arr: print s
Input:
A
e
a
D
f
B
Output (current):
A
B
D
a
e
f
Output (should be):
a
e
f
A
B
D
解决方案
Use a custom key method which checks whether the item is not .lower() and then compares the items itself. For 'A', 'D' and 'B' not x.islower() will return True and for other it is False, as True > False smaller case items will come first:
>>> arr = ['A','e','a','D','f','B']
>>> arr.sort(key=lambda x:(not x.islower(), x))
>>> arr
['a', 'e', 'f', 'A', 'B', 'D']