ホームページ バックエンド開発 Python チュートリアル Python のタプルと辞書の詳細な紹介

Python のタプルと辞書の詳細な紹介

Mar 20, 2017 am 09:45 AM

1. タプル

(1,2,3,4)
('olive',123)
("python",)
ログイン後にコピー

の式

a=tuple((1,2,3,))
b=("python",)
ログイン後にコピー
2. タプル関数

属性

class tuple(object):
    """
    tuple() -> empty tuple
    tuple(iterable) -> tuple initialized from iterable's items
    
    If the argument is a tuple, the return value is the same object.
    """
    def count(self, value): # real signature unknown; restored from __doc__
        """ T.count(value) -> integer -- return number of occurrences of value """
        return 0
    def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
        """
        T.index(value, [start, [stop]]) -> integer -- return first index of value.
        Raises ValueError if the value is not present.
        """
        return 0
    def __add__(self, *args, **kwargs): # real signature unknown
        """ Return self+value. """
        pass
    def __contains__(self, *args, **kwargs): # real signature unknown
        """ Return key in self. """
        pass
    def __eq__(self, *args, **kwargs): # real signature unknown
        """ Return self==value. """
        pass
    def __getattribute__(self, *args, **kwargs): # real signature unknown
        """ Return getattr(self, name). """
        pass
    def __getitem__(self, *args, **kwargs): # real signature unknown
        """ Return self[key]. """
        pass
    def __getnewargs__(self, *args, **kwargs): # real signature unknown
        pass
    def __ge__(self, *args, **kwargs): # real signature unknown
        """ Return self>=value. """
        pass
    def __gt__(self, *args, **kwargs): # real signature unknown
        """ Return self>value. """
        pass
    def __hash__(self, *args, **kwargs): # real signature unknown
        """ Return hash(self). """
        pass
    def __init__(self, seq=()): # known special case of tuple.__init__
        """
        tuple() -> empty tuple
        tuple(iterable) -> tuple initialized from iterable's items
        
        If the argument is a tuple, the return value is the same object.
        # (copied from class doc)
        """
        pass
    def __iter__(self, *args, **kwargs): # real signature unknown
        """ Implement iter(self). """
        pass
    def __len__(self, *args, **kwargs): # real signature unknown
        """ Return len(self). """
        pass
    def __le__(self, *args, **kwargs): # real signature unknown
        """ Return self<=value. """
        pass
    def __lt__(self, *args, **kwargs): # real signature unknown
        """ Return self<value. """
        pass
    def __mul__(self, *args, **kwargs): # real signature unknown
        """ Return self*value.n """
        pass
    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass
    def __ne__(self, *args, **kwargs): # real signature unknown
        """ Return self!=value. """
        pass
    def __repr__(self, *args, **kwargs): # real signature unknown
        """ Return repr(self). """
        pass
    def __rmul__(self, *args, **kwargs): # real signature unknown
        """ Return self*value. """
        pass
tuple
ログイン後にコピー
3. タプルはリストとよく似ていますが、タプルの要素は変更できないため、リストにある多くの関数はタプルでは使用できません。

1) count(self, value):

タプル内の value 要素の数をカウントし、int 値を返します。

a=(1,2,3,4,1,2,3,1,2,)
b=a.count(1)
print(a,type(a))
print(b,type(b))
#运行结果
(1, 2, 3, 4, 1, 2, 3, 1, 2) <class &#39;tuple&#39;>
3 <class &#39;int&#39;>
demo
ログイン後にコピー

2)index(self, value, start=None, stop=None):

index

、タプル内でvalue要素が最初に出現する位置を見つけます。startパラメータとstopパラメータは検索開始です。終了位置 (デフォルトは None) は int 値を返します。この要素が検索に含まれていない場合は、「ValueError: 'f' is not in tuple」が返されます。

a=(1,2,3,4,1,2,3,1,2,)
b=a.index(3)
print(a,len(a))
print(b,type(b))
#运行结果
(1, 2, 3, 4, 1, 2, 3, 1, 2) 9
2 <class &#39;int&#39;>
demo
ログイン後にコピー

3) add(self, *args, **kwargs):

新しい要素をタプルに追加します。新しいタプルを生成するには、追加された新しい要素をタプルの形式で追加する必要があります。

a=(1,2,3,4)
b=a.__add__((5,1))   #括号理给出的必须是元组
print(a,type(a))
print(b,type(b))
#运行结果
(1, 2, 3, 4) <class &#39;tuple&#39;>
(1, 2, 3, 4, 5, 1) <class &#39;tuple&#39;>
demo
ログイン後にコピー

4) contains(self, *args, **kwargs):

タプルに要素が含まれているかどうかを判断し、ブール値を返します。

a=(1,2,3,4,1,2,3,1,2,)
b=a.__contains__(2)
c=a.__contains__(5)
print(a)
print(b)
print(c)
#运行结果
(1, 2, 3, 4, 1, 2, 3, 1, 2)
True
False
demo
ログイン後にコピー

2. 辞書

1. 辞書式

{"name":"olive","age":18}
ログイン後にコピー
辞書の作成:

a={"name":"olive","age":18}
b=dict({"name":"lusi","age":18})
ログイン後にコピー

2. 辞書の機能属性

class dict(object):
    """
    dict() -> new empty dictionary
    dict(mapping) -> new dictionary initialized from a mapping object's
        (key, value) pairs
    dict(iterable) -> new dictionary initialized as if via:
        d = {}
        for k, v in iterable:
            d[k] = v
    dict(**kwargs) -> new dictionary initialized with the name=value pairs
        in the keyword argument list.  For example:  dict(one=1, two=2)
    """
    def clear(self): # real signature unknown; restored from __doc__
        """ D.clear() -> None.  Remove all items from D. """
        pass
    def copy(self): # real signature unknown; restored from __doc__
        """ D.copy() -> a shallow copy of D """
        pass
    @staticmethod # known case
    def fromkeys(*args, **kwargs): # real signature unknown
        """ Returns a new dict with keys from iterable and values equal to value. """
        pass
    def get(self, k, d=None): # real signature unknown; restored from __doc__
        """ D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None. """
        pass
    def items(self): # real signature unknown; restored from __doc__
        """ D.items() -> a set-like object providing a view on D's items """
        pass
    def keys(self): # real signature unknown; restored from __doc__
        """ D.keys() -> a set-like object providing a view on D's keys """
        pass
    def pop(self, k, d=None): # real signature unknown; restored from __doc__
        """
        D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
        If key is not found, d is returned if given, otherwise KeyError is raised
        """
        pass
    def popitem(self): # real signature unknown; restored from __doc__
        """
        D.popitem() -> (k, v), remove and return some (key, value) pair as a
        2-tuple; but raise KeyError if D is empty.
        """
        pass
    def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
        """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """
        pass
    def update(self, E=None, **F): # known special case of dict.update
        """
        D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
        If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
        If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
        In either case, this is followed by: for k in F:  D[k] = F[k]
        """
        pass
    def values(self): # real signature unknown; restored from __doc__
        """ D.values() -> an object providing a view on D's values """
        pass
    def __contains__(self, *args, **kwargs): # real signature unknown
        """ True if D has a key k, else False. """
        pass
    def __delitem__(self, *args, **kwargs): # real signature unknown
        """ Delete self[key]. """
        pass
    def __eq__(self, *args, **kwargs): # real signature unknown
        """ Return self==value. """
        pass
    def __getattribute__(self, *args, **kwargs): # real signature unknown
        """ Return getattr(self, name). """
        pass
    def __getitem__(self, y): # real signature unknown; restored from __doc__
        """ x.__getitem__(y) <==> x[y] """
        pass
    def __ge__(self, *args, **kwargs): # real signature unknown
        """ Return self>=value. """
        pass
    def __gt__(self, *args, **kwargs): # real signature unknown
        """ Return self>value. """
        pass
    def __init__(self, seq=None, **kwargs): # known special case of dict.__init__
        """
        dict() -> new empty dictionary
        dict(mapping) -> new dictionary initialized from a mapping object's
            (key, value) pairs
        dict(iterable) -> new dictionary initialized as if via:
            d = {}
            for k, v in iterable:
                d[k] = v
        dict(**kwargs) -> new dictionary initialized with the name=value pairs
            in the keyword argument list.  For example:  dict(one=1, two=2)
        # (copied from class doc)
        """
        pass
    def __iter__(self, *args, **kwargs): # real signature unknown
        """ Implement iter(self). """
        pass
    def __len__(self, *args, **kwargs): # real signature unknown
        """ Return len(self). """
        pass
    def __le__(self, *args, **kwargs): # real signature unknown
        """ Return self<=value. """
        pass
    def __lt__(self, *args, **kwargs): # real signature unknown
        """ Return self<value. """
        pass
    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass
    def __ne__(self, *args, **kwargs): # real signature unknown
        """ Return self!=value. """
        pass
    def __repr__(self, *args, **kwargs): # real signature unknown
        """ Return repr(self). """
        pass
    def __setitem__(self, *args, **kwargs): # real signature unknown
        """ Set self[key] to value. """
        pass
    def __sizeof__(self): # real signature unknown; restored from __doc__
        """ D.__sizeof__() -> size of D in memory, in bytes """
        pass
    __hash__ = None
dict
ログイン後にコピー

3.

1 )clear(self):

辞書内のすべての要素をクリアします。

a={"name":"olive","age":18}
b=a.clear()
print(a)
print(b)
#运行结果
{}
None
ログイン後にコピー

2) copy(self):

タプルをコピーします。これは浅いコピーに相当します。

a={"name": "olive","age":18}
b=a.copy()
print(a,id(a),id("name"))
print(b,id(b),id("name"))
#赋值
c={"name": "lusi","age":18}
d=c
print(c,id("name"))
print(d,id("name"))
#浅拷贝
e={"name": "shy","age":18}
f=copy.copy(e)
print(e,id(e),id("name"))
print(f,id(f),id("name"))
#运行结果
{'name': 'olive', 'age': 18} 2915224 2019840
{'name': 'olive', 'age': 18} 2915304 2019840
{'name': 'lusi', 'age': 18} 2019840
{'name': 'lusi', 'age': 18} 2019840
{'name': 'shy', 'age': 18} 5584616 2019840
{'name': 'shy', 'age': 18} 5586056 2019840
ログイン後にコピー

3) fromkeys(*args, **kwargs):[fromkeys(seq,value=None)]

seq を辞書のキー、value を辞書の値として使用して、新しい辞書を作成します。 、デフォルトは「なし」です。同じ値の辞書を作成するのに適しています。

a={"hunan": "changsha","guangdong":"guangzhou","jiangsu":"nanjing",'hubei':"wuhan"}
b=dict.fromkeys(a,"good")
c=dict.fromkeys(["a","b","c"],"abc")
d=dict.fromkeys("abcc")           
print(a)
print(b)
print(c)
print(d)
#运行结果
{'guangdong': 'guangzhou', 'hubei': 'wuhan', 'hunan': 'changsha', 'jiangsu': 'nanjing'}
{'hubei': 'good', 'guangdong': 'good', 'hunan': 'good', 'jiangsu': 'good'}
{'c': 'abc', 'b': 'abc', 'a': 'abc'}
{'c': None, 'b': None, 'a': None}   #seq给出的字符串c是重复的,但是创建的键只取一个。
ログイン後にコピー

4) get(self, k, d=None):

辞書内のキー k の値を取得します。 k が辞書に含まれていない場合は、d の値が与えられ、d になります。デフォルトは「なし」です。

a={"a":1,"b":2,"c":3,"d":4}
b=a.get("a")
c=a.get("e")
d=a.get("e",5)
print(a)
print(b)
print(c)
print(d)
#运行结果
{'b': 2, 'a': 1, 'c': 3, 'd': 4}
1
None
5
ログイン後にコピー

5)

items(self):

辞書を走査し、辞書内のキーと値のペアごとにタプルを形成し、これらのタプルをリストのような dict_items で返すメソッド。

a={"a":1,"b":2,"c":3,"d":4}
b=a.items()
print(a)
print(b,type(b))
#运行结果
{'d': 4, 'c': 3, 'a': 1, 'b': 2}
dict_items([('d', 4), ('c', 3), ('a', 1), ('b', 2)]) <class &#39;dict_items&#39;>
ログイン後にコピー
6)keys(self):

辞書キーのキーを走査し、リストのような dict_keys を返すメソッド。これは items メソッドと同じです。

a={"a":1,"b":2,"c":3,"d":4}
b=a.keys()
print(a)
print(b,type(b))
#运行结果
{'b': 2, 'a': 1, 'c': 3, 'd': 4}
dict_keys(['b', 'a', 'c', 'd']) <class &#39;dict_keys&#39;>
ログイン後にコピー
7)values(self):

辞書の値 value を走査し、リストのような dict_values を返すメソッド。これは items メソッドと同じです。

a={"a":1,"b":2,"c":3,"d":4}
b=a.values()
print(a)
print(b,type(b))
#运行结果
{'c': 3, 'd': 4, 'b': 2, 'a': 1}
dict_values([3, 4, 2, 1]) <class &#39;dict_values&#39;>
ログイン後にコピー

8)pop(self, k, d=None):

はgetメソッドと似ていますが、getは辞書内のキーkを持つ値を取得するのに対し、popは辞書内のキー k の値を取り出します。キー k が辞書に含まれておらず、d がデフォルト値ではない場合、取得される値は d の値です。d がデフォルト値 None の場合、KeyError が報告されます。

a={"a":1,"b":2,"c":3,"d":4}
b=a.pop("a")
c=a.pop("e","five")
print(a)
print(b,type(b))
print(c,type(c))
#运行结果
{'c': 3, 'd': 4, 'b': 2}
1 <class &#39;int&#39;>
five <class &#39;str&#39;>
ログイン後にコピー

9)popitem(自分):

从字典中随机取出一组键值,返回一个新的元组。如果字典中无键值可取,则KeyError报错。

a={"a":1,"b":2,"c":3,"d":4}
b=a.popitem()
print(a)
print(b,type(b))
#运行结果
{'d': 4, 'b': 2, 'a': 1}
('c', 3) <class &#39;tuple&#39;>
ログイン後にコピー

10)setdefault(self, k, d=None):

从字典中获取键为k的值,当字典中包含键k值时,功能和get基本一致,当字典中不包含键k值时,在原字典上添加上键为k的初始键值对,并返回值d。

a={"a":1,"b":2,"c":3,"d":4}
b=a.setdefault("a")
c=a.setdefault("e")
d=a.setdefault("f",6)
print(a)
print(b)
print(c)
print(d)
#运行结果
{'f': 6, 'c': 3, 'a': 1, 'e': None, 'b': 2, 'd': 4}
1
None
6
ログイン後にコピー

11)update(self, E=None, **F):

给字典新增元素,没有返回值。用法:dict.update(dict2)。

a={"a":1,"b":2,"c":3,"d":4}
b=a.update({"e":5})
print(a)
print(b)
#运行结果
{'c': 3, 'b': 2, 'd': 4, 'a': 1, 'e': 5}
None
ログイン後にコピー

12)contains(self, *args, **kwargs):

判断列表中是否包含某个键值对,返回布尔值。用法:dict.contains(keys)。

a={"a":1,"b":2,"c":3,"d":4}
b=a.__contains__("a")
print(a)
print(b)
#运行结果
{'a': 1, 'd': 4, 'c': 3, 'b': 2}
True
ログイン後にコピー

13)delitem(self, *args, **kwargs):

删除字典中的某个键值对,没有返回值。用法:dict.delitem(keys)。

a={"a":1,"b":2,"c":3,"d":4}
b=a.__delitem__("a")
print(a)
print(b)
#运行结果
{'c': 3, 'b': 2, 'd': 4}
None
ログイン後にコピー

以上がPython のタプルと辞書の詳細な紹介の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

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

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

LinuxターミナルでPythonバージョンを表示するときに発生する権限の問題を解決する方法は? LinuxターミナルでPythonバージョンを表示するときに発生する権限の問題を解決する方法は? Apr 01, 2025 pm 05:09 PM

LinuxターミナルでPythonバージョンを表示する際の許可の問題の解決策PythonターミナルでPythonバージョンを表示しようとするとき、Pythonを入力してください...

プロジェクトの基本と問題駆動型の方法で10時間以内にコンピューター初心者プログラミングの基本を教える方法は? プロジェクトの基本と問題駆動型の方法で10時間以内にコンピューター初心者プログラミングの基本を教える方法は? Apr 02, 2025 am 07:18 AM

10時間以内にコンピューター初心者プログラミングの基本を教える方法は?コンピューター初心者にプログラミングの知識を教えるのに10時間しかない場合、何を教えることを選びますか...

中間の読書にどこでもfiddlerを使用するときにブラウザによって検出されないようにするにはどうすればよいですか? 中間の読書にどこでもfiddlerを使用するときにブラウザによって検出されないようにするにはどうすればよいですか? Apr 02, 2025 am 07:15 AM

fiddlereveryversings for the-middleの測定値を使用するときに検出されないようにする方法

あるデータフレームの列全体を、Python内の異なる構造を持つ別のデータフレームに効率的にコピーする方法は? あるデータフレームの列全体を、Python内の異なる構造を持つ別のデータフレームに効率的にコピーする方法は? Apr 01, 2025 pm 11:15 PM

PythonのPandasライブラリを使用する場合、異なる構造を持つ2つのデータフレーム間で列全体をコピーする方法は一般的な問題です。 2つのデータがあるとします...

uvicornは、serving_forever()なしでhttpリクエストをどのように継続的に聞いていますか? uvicornは、serving_forever()なしでhttpリクエストをどのように継続的に聞いていますか? Apr 01, 2025 pm 10:51 PM

UvicornはどのようにしてHTTPリクエストを継続的に聞きますか? Uvicornは、ASGIに基づく軽量のWebサーバーです。そのコア機能の1つは、HTTPリクエストを聞いて続行することです...

文字列を介してオブジェクトを動的に作成し、Pythonでメソッドを呼び出す方法は? 文字列を介してオブジェクトを動的に作成し、Pythonでメソッドを呼び出す方法は? Apr 01, 2025 pm 11:18 PM

Pythonでは、文字列を介してオブジェクトを動的に作成し、そのメソッドを呼び出す方法は?これは一般的なプログラミング要件です。特に構成または実行する必要がある場合は...

See all articles