Last active
November 6, 2015 01:56
-
-
Save tokibito/f3847c33207ca741b3d8 to your computer and use it in GitHub Desktop.
python sort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
def _sort_key(record): | |
""" | |
金額部分を数値型に変換して返す | |
30円 -> 30 | |
""" | |
price = int(record[2][:-1]) | |
return price | |
def _sort_cmp(record1, record2): | |
"""にんじんが常に先頭に来るような比較関数 | |
""" | |
if record1[1] == u'にんじん': | |
return -1 | |
elif record2[1] == u'にんじん': | |
return 1 | |
# それ以外はデフォルトのcmp関数を使う | |
return cmp(record1, record2) | |
def main(): | |
data = [ | |
['00003', u'みかん', u'30円'], | |
['00001', u'りんご', u'100円'], | |
['00004', u'にんじん', u'40円'], | |
['00002', u'たまねぎ', u'50円'], | |
] | |
print "--- original ---" | |
for record in data: | |
print u'{}, {}, {}'.format(*record) | |
# data.sort() | |
# data.sort(key=_sort_key) | |
data.sort(cmp=_sort_cmp) | |
print "--- sorted ---" | |
for record in data: | |
print u'{}, {}, {}'.format(*record) | |
if __name__ == '__main__': | |
main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import functools | |
def _sort_key(record): | |
""" | |
金額部分を数値型に変換して返す | |
30円 -> 30 | |
""" | |
price = int(record[2][:-1]) | |
return price | |
def _sort_cmp(record1, record2): | |
"""にんじんが常に先頭に来るような比較関数 | |
""" | |
if record1[1] == 'にんじん': | |
return -1 | |
elif record2[1] == 'にんじん': | |
return 1 | |
# cmp関数が廃止されたので自前で比較 | |
elif record1[0] == record2[0]: | |
return 0 | |
elif record1[0] >= record2[0]: | |
return 1 | |
return -1 | |
def main(): | |
data = [ | |
['00003', 'みかん', '30円'], | |
['00001', 'りんご', '100円'], | |
['00004', 'にんじん', '40円'], | |
['00002', 'たまねぎ', '50円'], | |
] | |
print("--- original ---") | |
for record in data: | |
print('{}, {}, {}'.format(*record)) | |
# data.sort() | |
# data.sort(key=_sort_key) | |
data.sort(key=functools.cmp_to_key(_sort_cmp)) | |
print("--- sorted ---") | |
for record in data: | |
print('{}, {}, {}'.format(*record)) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment