10 List_comprehension

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]:
['A', 'E', 'A', 'I']
In [2]:
1# list comprehention
print([[ i*j for j in range(4)] for i in range(6)])
[[0, 0, 0, 0], [0, 1, 2, 3], [0, 2, 4, 6], [0, 3, 6, 9], [0, 4, 8, 12], [0, 5, 10, 15]]
In [3]:
print("\n".join(["%d * %d = %d" %(a,b,a*b) for a in range(2,4) 
                                            for b in range(1,4)]))
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
In [4]:
oldlist = [1, 2, 'A', False, 3]
 
newlist = [i*i for i in oldlist if type(i)==int]
newlist
Out[4]:
[1, 4, 9]
In [5]:
# Dictionary comprehention
d = {n: n**2 for n in range(5)}
print(d)
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
In [6]:
d = {n: True for n in range(5)}
print(d)
{0: True, 1: True, 2: True, 3: True, 4: True}
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)
{1: 1, 3: 9, 9: 81, 5: 25, 7: 49}
In [8]:
a = {'k':'v','k2':3}
print({key: values for key,values in a.items()})
{'k2': 3, 'k': 'v'}


© 2017. All rights reserved.

Powered by ZooFighter v0.12