[python]zip関数

12558 ワード

2 Dリストを反転


作成したメソッド
import numpy as np

mylist = [[1,2,3], [4,5,6], [7,8,9]]
a = np.array(mylist)
ans = a.T
print(type(ans.tolist())) # ndarray type에서 list 타입으로 변환 후 출력코드
#print(np.transpose(a))
'''
import numpy as np
def solution(mylist):
    ans = np.transpose(mylist)
    return ans.tolist()
'''
通常のリストのrowとcolumnを反転します.
mylist = [[1,2,3], [4,5,6], [7,8,9]]
new_list = [[],[],[]]
for i in range(len(mylist)) :
    for j in range(len(mylist[i])) :
        new_list[i].append(mylist[i][j])
zipと解包を利用する
mylist = [[1,2,3], [4,5,6], [7,8,9]]
new_list = list(map(list, zip(*mylist)))
print(new_list)

zipの使用


さまざまな使い方
# This is similar to transposing a matrix.
for item in zip([1,2,3], ['sugar', 'spice', 'everthing']) :
    print(item)

print(list(zip(range(3), ['fee','fi','fo','fum'])))
[(0, 'fee'), (1,'fi'), (2,'fo')]
複数のiterableを同時に巡回する場合
list1 = [1, 2, 3, 4]
list2 = [100, 120, 30, 300]
list3 = [392, 2, 33, 1]
answer = []
for number1, number2, number3 in zip(list1, list2, list3):
   print(number1 + number2 + number3)
キーリストと値リストを使用してディックマニュアルを作成する
animals = ['cat', 'dog', 'lion']
sounds = ['meow', 'woof', 'roar']
answer = dict(zip(animals, sounds))