Python

[Python] python comprehension

jjingle 2024. 1. 31. 11:47

Python comprehension ?

๋‹ค๋ฅธ Sequence๋กœ๋ถ€ํ„ฐ ์ƒˆ๋กœ์šด Sequence (Iterable Object)๋ฅผ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ๊ธฐ๋Šฅ
* comprehension :  ์ดํ•ด๋ ฅ 

 

 

01. List comprehension

[ ์ถœ๋ ฅ ํ‘œํ˜„์‹ for ์š”์†Œ in ์ž…๋ ฅ Sequence [ if ์กฐ๊ฑด์‹ ] ]
  • ์ž…๋ ฅ Sequence๋Š” Iteration์ด ๊ฐ€๋Šฅํ•œ ๋ฐ์ดํ„ฐ Sequence ํ˜น์€ ์ปฌ๋ ‰์…˜
  • [if ์กฐ๊ฑด์‹]์€ ์˜ต์…˜
hash_table = list([0 for i in range(10)])

print(hash_table) #[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]


#1. ์ข…๋ฅ˜๊ฐ€ ๋‹ค๋ฅธ ๋ฐ์ดํ„ฐ์—์„œ ์ •์ˆ˜ ๋ฆฌ์ŠคํŠธ๋งŒ ๊ฐ€์ ธ์˜ค๊ธฐ
dataset = [4, True, 'dave', 2.1, 3]
int_data = [num for num num in dataset if type(num) == int]

print(int_data) #[4, 3]

 


02. Set comprehension 

{ ์ถœ๋ ฅ ํ‘œํ˜„์‹ for ์š”์†Œ in ์ž…๋ ฅ Sequence [ if ์กฐ๊ฑด์‹ ] }
  • ์ž…๋ ฅ Sequence๋กœ๋ถ€ํ„ฐ ์กฐ๊ฑด์— ๋งž๋Š” ์ƒˆ๋กœ์šด Set ์ปฌ๋ ‰์…˜ ๋ฆฌํ„ด ( Set : ์ค‘๋ณต X )
  • [if ์กฐ๊ฑด์‹]์€ ์˜ต์…˜
  • Python3 ๋ถ€ํ„ฐ ์ถ”๊ฐ€๋จ
int_data = [1, 1, 2, 3, 3, 4]

square_data_set = {num * num for num in int_data}
print(square_data_set) #{16, 1, 4, 9}

square_data_set1 = {num * num for num in int_data if num > 3}
print(square_data_set) #{16}

03. Dictionary comprehension 

{ Key:Value for ์š”์†Œ in ์ž…๋ ฅ Sequence [ if ์กฐ๊ฑด์‹ ] }
  • ์ž…๋ ฅ Sequence๋กœ๋ถ€ํ„ฐ ์กฐ๊ฑด์— ๋งž๋Š” ์ƒˆ๋กœ์šด Dictionary ์ปฌ๋ ‰์…˜ ๋ฆฌํ„ด
  • [if ์กฐ๊ฑด์‹]์€ ์˜ต์…˜
  • Python3 ๋ถ€ํ„ฐ ์ถ”๊ฐ€๋จ
id_name = {1:'lee', 2:'kim', 3:'park'}
id_name.items() #dict_items([(1, 'lee'), (2, 'kim'), (3, 'park')])

#์•„์ด๋””๊ฐ€ 1๋ณด๋‹ค ํฐ ๋ฐ์ดํ„ฐ, val:key ํ˜•์‹์œผ๋กœ
name_id = {val:key for key,val in id_name.items() if key > 1}
print(name_id) #{'kim': 2, 'park': 3}

#์•„์ด๋”” 10๋‹จ์œ„๋กœ ๋ฐ”๊พธ๊ธฐ
name_id = {key*10:val for key,val in id_name.items()}
print(name_id) #{10:'lee', 20:'kim', 30:'park'}

'Python' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[Python] ๋ฐ์ฝ”๋ ˆ์ดํ„ฐ (Decorator)  (1) 2024.01.31