10 List_comprehension
| 4 Minute Read on Python
List Comprehension¶
- Python의 Comprehension은 한 Sequence가 다른 Sequence (Iterable Object)로부터 (변형되어) 구축될 수 있게한 기능이다
- List Comprehension는 입력 Sequence로부터 지정된 표현식에 따라 새로운 리스트 컬렉션을 생성한다.
- List Comprehension는 다음과 같이 표현된다.
- [output_expression() for(set of values to iterate) if(conditional filtering)]
- Dictionary Comprehension는 다음과 같이 표현된다.
- {Key:Value for 요소 in 입력 Sequence [if 조건식]}
In [1]:
[x for x in 'MATHEMATICS' if x in ['A','E','I','O','U']]
Out[1]:
In [2]:
1# list comprehention
print([[ i*j for j in range(4)] for i in range(6)])
In [3]:
print("\n".join(["%d * %d = %d" %(a,b,a*b) for a in range(2,4)
for b in range(1,4)]))
In [4]:
oldlist = [1, 2, 'A', False, 3]
newlist = [i*i for i in oldlist if type(i)==int]
newlist
Out[4]:
In [5]:
# Dictionary comprehention
d = {n: n**2 for n in range(5)}
print(d)
In [6]:
d = {n: True for n in range(5)}
print(d)
In [7]:
# Dictionary comprehention
def isodd(val):
return val % 2 == 1
mydict = {x:x*x for x in range(11) if isodd(x)}
print(mydict)
In [8]:
a = {'k':'v','k2':3}
print({key: values for key,values in a.items()})