리스트 컴프리헨션
# list 생성
l = [i for i in range(10)]
print(l) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# 이런식으로도 가능
l = [f'{i}입니다!' for i in range(10)]
print(l) # ['0입니다!', '1입니다!', '2입니다!', '3입니다!', '4입니다!', '5입니다!', '6입니다!', '7입니다!', '8입니다!', '9입니다!']
# 구구단 출력
l = [f'{i} X {j} = {i*j}' for i in range(2, 10) for j in range(1, 10)]
print(l) # ['2 X 1 = 2', '2 X 2 = 4', '2 X 3 = 6', '2 X 4 = 8', '2 X 5 = 10', '2 X 6 = 12', '2 X 7 = 14', '2 X 8 = 16', '2 X 9 = 18', '3 X 1 = 3', '3 X 2 = 6', '3 X 3 = 9', '3 X 4 = 12', '3 X 5 = 15', '3 X 6 = 18', '3 X 7 = 21', '3 X 8 = 24', '3 X 9 = 27', '4 X 1 = 4', '4 X 2 = 8', '4 X 3 = 12', '4 X 4 = 16', '4 X 5 = 20', '4 X 6 = 24', '4 X 7 = 28', '4 X 8 = 32', '4 X 9 = 36', '5 X 1 = 5', '5 X 2 = 10', '5 X 3 = 15', '5 X 4 = 20', '5 X 5 = 25', '5 X 6 = 30', '5 X 7 = 35', '5 X 8 = 40', '5 X 9 = 45', '6 X 1 = 6', '6 X 2 = 12', '6 X 3 = 18', '6 X 4 = 24', '6 X 5 = 30', '6 X 6 = 36', '6 X 7 = 42', '6 X 8 = 48', '6 X 9 = 54', '7 X 1 = 7', '7 X 2 = 14', '7 X 3 = 21', '7 X 4 = 28', '7 X 5 = 35', '7 X 6 = 42', '7 X 7 = 49', '7 X 8 = 56', '7 X 9 = 63', '8 X 1 = 8', '8 X 2 = 16', '8 X 3 = 24', '8 X 4 = 32', '8 X 5 = 40', '8 X 6 = 48', '8 X 7 = 56', '8 X 8 = 64', '8 X 9 = 72', '9 X 1 = 9', '9 X 2 = 18', '9 X 3 = 27', '9 X 4 = 36', '9 X 5 = 45', '9 X 6 = 54', '9 X 7 = 63', '9 X 8 = 72', '9 X 9 = 81']
# if 문은 뒤에 붙임
l = [i for i in range(10) if i % 2 == 0]
print(l)
# if else 문은 앞에 붙임
l = [i if i % 2 == 0 else None for i in range(10)]
print(l) # [0, None, 2, None, 4, None, 6, None, 8, None]
# elif 는 이렇게 씀
l = ['1' if i == 1 else '3' if i == 3 else None for i in range(5)]
print(l) # [None, '1', None, '3', None]
삼항 연산자
x = 5
y = 10
result = 'x is greater' if x > y else 'y is greater or equal'
print(result) # 출력: 'y is greater or equal'
'Python' 카테고리의 다른 글
Python(12) 클래스 (0) | 2023.09.17 |
---|---|
Python(11) if, match, for, while 문 (0) | 2023.09.15 |
Python(9) 튜플, 딕셔너리, Set(집합) (0) | 2023.09.13 |
Python(8) 리스트 (0) | 2023.09.12 |
Python(7) 함수 (0) | 2023.09.12 |