Heim  >  Artikel  >  Backend-Entwicklung  >  Einführung in die Verwendung von setdefault in Python3 (Code)

Einführung in die Verwendung von setdefault in Python3 (Code)

不言
不言Original
2018-09-13 16:44:562805Durchsuche

Der Inhalt dieses Artikels befasst sich mit der Verwendung von setdefault in Python3. Er hat einen gewissen Referenzwert. Ich hoffe, dass er für Sie hilfreich ist.

Wenn das Wörterbuch d[k] den richtigen Schlüssel nicht finden kann, löst Python eine Ausnahme aus. Gibt es eine elegante Möglichkeit, diese Situation zu vermeiden?

index0.py Ruft ab Worthäufigkeitsinformationen aus dem Index und schreibt sie in die Liste – ohne 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!

zu verwenden, um python3 index0.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 verwendet dict.setdefault, um das Problem des Abrufens und Aktualisierens der Vorkommensliste von Wörtern in nur einer Zeile zu lösen

#!/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])

Mit anderen Worten:

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

ist äquivalent zu

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

Die beiden haben den gleichen Effekt, außer dass setdefault den gesamten Vorgang nur einmal abschließen muss, während letzteres zwei Abfragen erfordert

Verwandte Empfehlungen:


Wörterbücher in Python manipulieren Die Verwendung von die setdefault()-Methode

Einführung in die Verwendung von super() und __class__ in Python3

Das obige ist der detaillierte Inhalt vonEinführung in die Verwendung von setdefault in Python3 (Code). Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn