Python
 Computer >> コンピューター >  >> プログラミング >> Python

Python zip()関数


zip() 関数は、複数のイテレータをグループ化するために使用されます。 zip()のドキュメントをご覧ください ヘルプを使用して機能する 方法。次のコードを実行して、 zip()のヘルプを取得します 機能。

help(zip)

上記のプログラムを実行すると、次の結果が得られます。

出力

Help on class zip in module builtins:
class zip(object)
   | zip(iter1 [,iter2 [...]]) --> zip object
   |
   | Return a zip object whose .__next__() method returns a tuple where
   | the i-th element comes from the i-th iterable argument. The .__next__()
   | method continues until the shortest iterable in the argument sequence
   | is exhausted and then it raises StopIteration.
   |
   | Methods defined here:
   |
   | __getattribute__(self, name, /)
   | Return getattr(self, name).
   |
   | __iter__(self, /)
   | Implement iter(self).
   |
   | __new__(*args, **kwargs) from builtins.type
   | Create and return a new object. See help(type) for accurate signature.
   |
   | __next__(self, /)
   | Implement next(self).
   |
   | __reduce__(...)
   | Return state information for pickling.

それがどのように機能するかの簡単な例を見てみましょう?

## initializing two lists
names = ['Harry', 'Emma', 'John']
ages = [19, 20, 18]
## zipping both
## zip() will return pairs of tuples with corresponding elements from both lists
print(list(zip(names, ages)))

上記のプログラムを実行すると、次の結果が得られます

出力

[('Harry', 19), ('Emma', 20), ('John', 18)]

zipオブジェクトから要素を解凍することもできます。 *が前に付いたオブジェクトをzip()に渡す必要があります 働き。見てみましょう。

## initializing two lists
names = ['Harry', 'Emma', 'John']
ages = [19, 20, 18]
## zipping both
## zip() will return pairs of tuples with corresponding elements from both lists
zipped = list(zip(names, ages))
## unzipping
new_names, new_ages = zip(*zipped)
## checking new names and ages
print(new_names)
print(new_ages)

上記のプログラムを実行すると、次の結果が得られます。

('Harry', 'Emma', 'John')
(19, 20, 18)

zip()の一般的な使用法

これを使用して、異なるイテレータからの複数の対応する要素を一度に印刷できます。次の例を見てみましょう。

## initializing two lists
names = ['Harry', 'Emma', 'John']
ages = [19, 20, 18]
## printing names and ages correspondingly using zip()
for name, age in zip(names, ages):
print(f"{name}'s age is {age}")

上記のプログラムを実行すると、次の結果が得られます。

出力

Harry's age is 19
Emma's age is 20
John's age is 18

  1. Pythonのissubset()関数

    この記事では、Python標準ライブラリで利用可能なissubset()関数の実装と使用法について学習します。 issubset()メソッドは、セットのすべての要素が別のセットに存在する場合(引数として渡される場合)はブール値のTrueを返し、それ以外の場合はブール値のFalseを返します。 下の図では、BはAのサブセットです。AとBが同一のセットである場合、AはBの適切なサブセットであることを意味します。これは、両方のセットに同じ要素が含まれていることを意味します。 構文 <set 1>.issubset(<set 2>) 戻り値 boolean True/

  2. Intersection()関数Python

    この記事では、任意のセットで実行できるintersection()関数について学習します。数学によると、共通部分とは、2つのセットから共通の要素を見つけることを意味します。 構文 <set name>.intersection(<set a1> <set a2> ……..) 戻り値 引数として渡されるセット内の共通要素。 例 set_1 = {'t','u','t','o','r','i','a','l&