python使用提案テクニック共有(三)


これは一連の文章で、主にpythonの使用提案と技巧を共有して、毎回3点を共有して、収穫があることを望みます。
1どうやってリストの重複要素を除去しますか?

my_list = [3, 2, 1, 1, 2, 3]
print my_list
# [3, 2, 1, 1, 2, 3]
unique_list = list(set(my_list))
print unique_list
# [1, 2, 3]
または

from collections import OrderedDict


my_list = [3, 2, 1, 1, 2, 3]
print my_list
# [3, 2, 1, 1, 2, 3]
unique_list = list(OrderedDict.fromkeys(my_list))
print unique_list
# [3, 2, 1]
前の方法はlistの要素順序を保持しません。後の方法はlistの要素順序を保持します。
2どのようにdictの値を読みますか?
おすすめしない方法

url_dict = {
  'google': 'https://www.google.com/',
  'github': 'https://github.com/',
  'facebook': 'https://www.facebook.com/',
}


print url_dict['facebook']
print url_dict['google']
print url_dict['github']
# print url_dict['baidu']
# KeyError: 'baidu'

# https://www.facebook.com/
# https://www.google.com/
# https://github.com/
おすすめの方法

url_dict = {
  'google': 'https://www.google.com/',
  'github': 'https://github.com/',
  'facebook': 'https://www.facebook.com/',
}

print url_dict.get('facebook', 'https://www.google.com/')
print url_dict.get('google', 'https://www.google.com/')
print url_dict.get('github', 'https://www.google.com/')
print url_dict.get('baidu', 'https://www.google.com/')

# https://www.facebook.com/
# https://www.google.com/
# https://github.com/
# https://www.google.com/
前の方法では存在しないkeyを読み取ると、KeyError、例えばprint url_dict[‘baidu’は辞書にbaiduが存在しないので、KeyErrorを招きます。後者の方法は辞書のget方法を使用しており、keyが存在しない場合、KeyErrerは発生しません。標準値を与えたら、デフォルト値に戻ります。さもなければ、Noneに戻ります。
3辞書の並べ替え方法

unordered_dict = {'c': 1, 'b': 2, 'a': 3}

print sorted(unordered_dict.items(), key=lambda e: e[1])
# [('c', 1), ('b', 2), ('a', 3)]

print sorted(unordered_dict.items(), key=lambda e: e[0])
# [('a', 3), ('b', 2), ('c', 1)]

print sorted(unordered_dict.items(), key=lambda e: e[1], reverse=True)
# [('a', 3), ('b', 2), ('c', 1)]
第一の方式は辞書のvalue昇順で並べ替えられ、第二の方式は辞書のkey昇順で並べられ、第三の方式は辞書のvalue降順で並べられ、第一の方式とは逆で、パラメータreverseがTrueであることを指定したからです。sorted関数の機能はとても強くて、辞書を並べ替えることができるだけではなくて、いかなるiterableオブジェクトも並べ替えることができて、深く理解したいならばhttps://docs.python.org/2.7/howto/sorting.html#sortinghowtoを押してください。
以上はpythonを使って提案の技巧を使って(3)の詳しい内容を分かち合って、更にpythonの提案と技巧の資料に関して私達のその他の関連している文章に注意して下さい!