본문으로 바로가기

 

 

List Comprehension

if __name__ == '__main__':
    x = int(input())
    y = int(input())
    z = int(input())
    n = int(input())
    code = [[i, j, k] for i in range(x+1) for j in range(y+1) for k in range(z+1) if i+j+k!=n]
    print(code)

 

해설

List Comprehension문법과 range함수 활용하여 만드는 반복문이다.
값이 [ ㅇ ← ㅇ ← ㅇ ] 순서로 채워지는 속성을 이용하여, 동일한 조건에서 range( ㅇ + 1)을 하면 된다.

 

List Comprehension

리스트(List)안에 for문이 포함된 코드이다.
for문에 비해 코드가 간결하고 직관적이다.

① List Comprehension 사용 전

>>> group = [1, 2, 3, 4]
>>> result = []
>>> for i in group:
... 	result.append(i*2)
    
>>> print(result)
[2, 4, 6, 8]

② List Comprehension 사용 후

>>> group = [1, 2, 3, 4]
>>> result = [i*2 for i in group]
>>> print(result)
[2, 4, 6, 8]

 

참고 (for문)

https://bohemihan.tistory.com/entry/HackerRank-Python-Solution-Loops

 

HackerRank Python Solution / Loops

Loops if __name__ == '__main__': n = int(input()) for i in range(n): print(i*i) 해설 반복문과 숫자형연산자를 활용한 프로그래밍이다. for문 >>> a = "aBc" >>> for c in s: ... print(s) ... aBc aBc aBc..

bohemihan.tistory.com