■ for문을 포함하는 리스트 내포(List Comprehension)를 사용하는 방법을 보여준다.
▶ 예제 코드 1 (PY)
1 2 3 4 5 6 7 8 9 10 11 |
sourceList = [1, 2, 3, 4] targetList = [n * 3 for n in sourceList] print(targetList) """ [3, 6, 9, 12] """ |
▶ 예제 코드 2 (PY)
1 2 3 4 5 6 7 8 9 10 11 |
sourceList = [1, 2, 3, 4] targetList = [n * 3 for n in sourceList if n % 2 == 0] print(targetList) """ [6, 12] """ |
※ list1의 항목들 중에서 짝수만 필터링한다.
▶ 예제 코드 3 (PY)
1 2 3 4 5 6 7 8 9 |
targetList = [x * y for x in range(1, 10) for y in range(1, 10)] print(targetList) """ [1, 2, 3, 4, 5, 6, 7, 8, 9, 2, 4, 6, 8, 10, 12, 14, 16, 18, 3, 6, 9, 12, 15, 18, 21, 24, 27, 4, 8, 12, 16, 20, 24, 28, 32, 36, 5, 10, 15, 20, 25, 30, 35, 40, 45, 6, 12, 18, 24, 30, 36, 42, 48, 54, 7, 14, 21, 28, 35, 42, 49, 56, 63, 8, 16, 24, 32, 40, 48, 56, 64, 72, 9, 18, 27, 36, 45, 54, 63, 72, 81] """ |
※ for문을 2개 이상 사용할 수 있다.
▶ 예제 코드 4 (PY)
1 2 3 4 5 6 7 8 9 10 11 |
sourceList = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] targetList = [x for row in sourceList for x in row] print(targetList) """ [1, 2, 3, 4, 5, 6, 7, 8, 9] """ |
▶ 예제 코드 5 (PY)
1 2 3 4 5 6 7 8 9 10 11 |
sourceList = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] targetList = [[x ** 2 for x in row] for row in sourceList] print(targetList) """ [[1, 4, 9], [16, 25, 36], [49, 64, 81]] """ |
▶ 예제 코드 6 (PY)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
sourceList = [[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]] targetList = [ x for sublist1 in sourceList for sublist2 in sublist1 for x in sublist2 ] print(targetList) """ [1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6] """ |
▶ 예제 코드 7 (PY)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
sourceLst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] targetList1 = [x for x in sourceLst if x > 4 if x % 2 == 0] targetList2 = [x for x in sourceLst if x > 4 and x % 2 == 0] print(targetList1) print(targetList2) """ [6, 8, 10] [6, 8, 10] """ |
▶ 예제 코드 8 (PY)
1 2 3 4 5 6 7 8 9 10 11 |
sourceList = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] targetList = [[x for x in row if x % 3 == 0] for row in sourceList if sum(row) >= 10] print(targetList) """ [[6], [9]] """ |