2차원 List 뒤집기
2021. 5. 1. 01:36ㆍPython
728x90
1. 2중 for문 - 다른 언어에서 사용 가능 방법
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[j][i])
for n in new_list:
print(n)
2. zip 이용 - 파이썬 다운 방법!
mylist = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
new_list = list(map(list, zip(*mylist)))
for n in new_list:
print(n)
※ zip 함수
Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables.
ex )
l1 = [1, 2, 3]
l2 = ['a', 'b', 'c']
l3 = ['apple', 'banana', 'cake']
print('for z in zip(l1, l2, l3):')
for z in zip(l1, l2, l3):
print(z)
print('-----------------------')
print('for z1, z2, z3 in zip(l1, l2, l3):')
for z1, z2, z3 in zip(l1, l2, l3):
print(z1, z2, z3)
- 결과
tip !
zip함수로 dictionary 만들기!
728x90
'Python' 카테고리의 다른 글
__getitem__ (0) | 2021.05.21 |
---|---|
Python argparse (0) | 2021.05.09 |
정규 표현식 (0) | 2021.04.29 |
추상 클래스(abstract class) (0) | 2021.04.08 |
[Python] pathlib (0) | 2021.03.24 |