[python] zip


zip

  • zip()iterableオブジェクトを因子として、各オブジェクトに含まれる要素を返すiterator
  • numbers=[1,2,3]
    letters=['A','B','C']
    for pair in zip(numbers,letters):
        print(pair)
    # ======== 출력 ======== #
    (1,'A')
    (2,'B')
    (3,'C')
    for number, upper, lower in zip("12345", "ABCDE", "abcde"):
        print(number, upper, lower)
    
    # ======== 출력 ======== #
    1 A a
    2 B b
    3 C c
    4 D d
    5 E e
    
    numbers = (1, 2, 3)
        letters = ("A", "B", "C")
        pairs = list(zip(numbers, letters))
    print(pairs)
    [(1, 'A'), (2, 'B'), (3, 'C')]

    dictとともに使用

    keys = [1, 2, 3]
    values = ["A", "B", "C"]
    dictionary=dict(zip(keys, values))
    
    print(dictionary)
    
    {1: 'A', 2: 'B', 3: 'C'}
    

    注意事項:長さごとに異なる

  • 最短の因子を基準にデータを作成し、残りは破棄される.
  • numbers = ["1", "2", "3"]
    letters = ["A"]
    arr=list(zip(numbers, letters))
    print(arr)
    # ======== 출력 ======== #
    [('1', 'A')]