ホームページ  >  記事  >  バックエンド開発  >  Python3 での setdefault の使用法 (コード) の紹介

Python3 での setdefault の使用法 (コード) の紹介

不言
不言オリジナル
2018-09-13 16:44:562805ブラウズ

この記事では、Python3 での setdefault の使用法 (コード) を紹介します。一定の参考値があります。必要な友人は参照してください。お役に立てば幸いです。

辞書 d[k] が正しいキーを見つけられない場合、Python は例外をスローします。この状況を回避するエレガントな方法はありますか? 答えは「はい」です。

index0.py単語の出現頻度情報をインデックスから取得してリストに書き込みます -- dict.setdefault

#!/usr/bin/env python
# coding=utf-8
import sys, re

WORD_RE = re.compile(r'\w+')

index = {}
with open(sys.argv[1], encoding='utf-8') as fp:
    for line_no, line in enumerate(fp, 1):
        for match in WORD_RE.finditer(line):
            word = match.group()
            column_no = match.start()+1
            location = (line_no, column_no)
            occurrences = index.get(word, [])
            occurrences.append(location)
            index[word] = occurrences

for word in sorted(index, key=str.upper):
    print(word, index[word])

zen.txt

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

を使用せずに python3index0.py zen.txt

a [(19, 48), (20, 53)]
Although [(11, 1), (16, 1), (18, 1)]
ambiguity [(14, 16)]
and [(15, 23)]
are [(21, 12)]
aren [(10, 15)]
at [(16, 38)]
bad [(19, 50)]
be [(15, 14), (16, 27), (20, 50)]
beats [(11, 23)]
Beautiful [(3, 1)]
better [(3, 14), (4, 13), (5, 11), (6, 12), (7, 9), (8, 11), (17, 8), (18, 25)]
break [(10, 40)]
by [(1, 20)]
cases [(10, 9)]
...
## を実行します#index.py は dict.setdefault を使用し、単語の出現リストの取得と更新の問題を解決するために 1 行だけを使用します。

#!/usr/bin/env python
# coding=utf-8
import sys, re

WORD_RE = re.compile(r'\w+')

index = {}
with open(sys.argv[1], encoding='utf-8') as fp:
    for line_no, line in enumerate(fp, 1):
        for match in WORD_RE.finditer(line):
            word = match.group()
            column_no = match.start()+1
            location = (line_no, column_no)
            index.setdefault(word, []).append(location)

for word in sorted(index, key=str.upper):
    print(word, index[word])

つまり、

my_dict.setdefault(key, []).append(new_value)

同等の Yu

if key not in my_dict:
    my_dict[key] = []
my_dict[key].append(new_value)

この 2 つは同じ効果がありますが、setdefault では操作全体を 1 回完了するだけで済むのに対し、後者では 2 つのクエリが必要である点が異なります。

関連する推奨事項:


Python での操作辞書setdefault() メソッド

Python での super() と __class__ の使用法3

以上がPython3 での setdefault の使用法 (コード) の紹介の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。