Comprehension

Published onesixx on

https://shoark7.github.io/programming/python/about-list-comprehension-python
shoark7 github: list comprehension에서 표현식을 두 개 넘게 쓰지 말자
"""
Comprehensions
"""
#=== Using list (dictionary, set) comprehension
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result1 = [n for n in numbers if n % 2 == 0]
result2 = [n for n in numbers if n % 3 == 0]
result3 = [n * n for n in numbers]

names = ['Alice', 'Bob', 'Charlie', 'David']
name_lengths = {name: len(name) for name in names}



#=== Using generator expression
evens = (n for n in numbers if n % 2 == 0)
multiples3 = (n for n in numbers if n % 3 == 0)
squared_numbers = (n * n for n in numbers)

for number  in evens:
    print(number)

for square in squared_numbers:
    print(square)  # 1, 4, 9, 16, 25

if-else expression

#=== Using if-else expression
condition = True
result = 'Yes' if condition else 'No'

if condition:
    result = 'Yes'
else:
    result = 'No'

#=== Using if-elif-else expression
condition1 = True
condition2 = False

if condition1:
    result = 'Yes'
elif condition2:
    result = 'Maybe'
else:
    result = 'No'

result = 'Yes' if condition1 else 'Maybe' if condition2 else 'No'
#=== Using try-except block
### Handle exceptions with try-except block
try:
    result = 1 / 0
except ZeroDivisionError:
    result = 'Cannot divide by zero'

#=== Using try-except-else block
### Handle exceptions with try-except-else block
try:
    result = 1 / 1
except ZeroDivisionError:
    result = 'Cannot divide by zero'
else:
    result = 'Division successful'

#=== Using try-except-finally block
### Handle exceptions with try-except-finally block
try:
    result = 1 / 1
except ZeroDivisionError:
    result = 'Cannot divide by zero'
finally:
    result = 'Division finished'

https://stackoverflow.com/questions/952914/how-do-i-make-a-flat-list-out-of-a-list-of-lists

nestedlist = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
# ==flat==> [1, 2, 3, 4, 5, 6, 7, 8, 9]

# way1
flat_list = [x for xs in nestedlist for x in xs]

# way2
def flatten(nestedlist):
    return [x for xs in nestedlist for x in xs]
flat_list = flatten(nestedlist)

# way3
flat_list = []
for xs in nestedlist:
    for x in xs:
        flat_list.append(x)        
pp = ['aa_b','cc_d']

[i.split('_') for i in pp ]
# [['aa', 'b'], ['cc', 'd']]

a = []
b = []
for i in pp:
    tmp = i.split('_')
    a.append(tmp[0])
    b.append(tmp[1])
a # ['aa', 'cc']
b # ['b', 'd']

기본 문법

[ ( 변수를 활용한 값 ) for ( 사용할 변수명 ) in ( iterable )]

size = 10
arr = [i * 2 for i in range(size)]
  • 변수를 활용한 값 : i * 2
  • 사용할 변수명 : i
  • iterable :  range 리스트, set, dict, tuple …

활용

조건문으로 필터링하기

리스트의 크기가 iterable에 같다. 하지만 if문으로 filtering할 수 있다. .

## 짝수
size = 10
[n for n in range(1, 11) if n % 2 == 0]

# [2, 4, 6, 8, 10]


##  2의 배수이고(AND) 3의 배수인 수만 필터링
[n for n in range(1, 31) if n % 2 == 0 if n % 3 == 0]

## 2의 배수이거나(OR) 3의 배수인 수만 필터링
[n for n in range(1, 16) if (n % 2)==0 or (n % 3)==0]


Categories: Python Basic

onesixx

Blog Owner

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x