์ƒˆ์†Œ์‹

๐Ÿ ํŒŒ์ด์ฌ (Python)

ํŒŒ์ด์ฌ(python) ๋ฆฌ์ŠคํŠธ ์ค‘๋ณต ์š”์†Œ ๊ฐœ์ˆ˜ ์ฐพ๊ธฐ (์นด์šดํŒ…) or ์ œ๊ฑฐ,์‚ญ์ œํ•˜๊ธฐ (try , except , count)

  • -

*์ค‘๋ณต์š”์†Œ ์นด์šดํŒ…ํ•˜๊ธฐ

 

*try, except ๋ฌธ ์‚ฌ์šฉ
count={}
lists = ["a","a","b",'apple','w','wf']
for i in lists:
    try: count[i] += 1
    except: count[i]=1
print(count)

๊ฒฐ๊ณผ๊ฐ’ : {'a': 2, 'b': 1, 'apple': 1, 'w': 1, 'wf': 1}

์˜ˆ์™ธ์ฒ˜๋ฆฌํ• ๋•Œ ์‚ฌ์šฉํ•˜๋Š” try except๋ฅผ ์ด๋Ÿฐ์‹์œผ๋กœ ์‚ฌ์šฉํ•˜๋Š”๊ฒƒ์€ ์ƒ๊ฐ ๋ชปํ•ด๋ณด์•˜๋‹ค. 

for๋ฌธ์„ ํ†ตํ•ด lists์˜ ์š”์†Œ๋ฅผ ํ•˜๋‚˜์”ฉ ๊บผ๋‚ด์–ด , count๋ผ๋Š” ์ด๋ฆ„์˜ ๋”•์…”๋„ˆ๋ฆฌ์— ๋„ฃ๋Š”๋‹ค.

์ด๋•Œ count(๋”•์…”๋„ˆ๋ฆฌ)์— ์ด๋ฏธ ์กด์žฌํ•˜๋Š” key๊ฐ’์ด๋ผ๋ฉด, try๋ฌธ์ด ์‹คํ–‰๋˜๋ฉฐ value์— +1์„ ํ•˜๊ฒŒ๋œ๋‹ค.

count(๋”•์…”๋„ˆ๋ฆฌ)์— ์—†๋Š” key๊ฐ’์ด๋ผ๋ฉด except๊ฐ€ ์‹คํ–‰๋˜๋ฉฐ value๋Š” ๊ทธ๋ƒฅ 1๋กœ ์ €์žฅ๋œ๋‹ค.

 

 

* count() ํ•จ์ˆ˜ ์ด์šฉ

lists = [1,1,1,2,2,3,4,"abc"]
cnt = lists.count(1)   # ์ •์ˆ˜ 1์ด ๋ช‡๊ฐœ์ธ์ง€ ์ฐพ๋Š”๋‹ค. ->> count("์ฐพ์„ ์š”์†Œ")     
print("%s์€, %d๊ฐœ ์žˆ์Šต๋‹ˆ๋‹ค." %(1, cnt))


๊ฒฐ๊ณผ๊ฐ’  >>>>>>>> 1์€, 3๊ฐœ ์žˆ์Šต๋‹ˆ๋‹ค.

 

 

 

 

*์ค‘๋ณต์š”์†Œ ์‚ญ์ œ, ์ œ๊ฑฐํ•˜๊ธฐ

 

SET ์ด์šฉํ•˜๊ธฐ
arr = ['but', 'i', 'wont', 'hesitate', 'no', 'more', 'no', 'more', 'it', 'cannot', 'wait', 'im', 'yours']


arr = set(arr) # "arr"๋ผ๋Š” ๋ฆฌ์ŠคํŠธ์˜ ๋ฐ์ดํ„ฐ ํƒ€์ž…์„ set์œผ๋กœ ๋ฐ”๊พผ๋‹ค.
#set์€ ์ค‘๋ณต์š”์†Œ๋ฅผ ํ—ˆ์šฉํ•˜์ง€ ์•Š๋Š” ๋ฐ์ดํ„ฐํ˜•ํƒœ์ด๊ธฐ ๋•Œ๋ฌธ์—, ์ค‘๋ณต์š”์†Œ๋“ค์ด ์ œ๊ฑฐ๋œ๋‹ค.
arr = list(list3)

๊ทธ๋ƒฅ ํ˜•ํƒœ๋ฅผ set์œผ๋กœ ๋ฐ”๊พธ์—ˆ๋‹ค๊ฐ€, ๋‹ค์‹œ list๋กœ ๋ฐ”๊พธ์–ด์ฃผ๋ฉด ๋œ๋‹ค. set์€ ์ค‘๋ณต์„ ํ—ˆ์šฉํ•˜์ง€ ์•Š๋Š” ์ž๋ฃŒํ˜•ํƒœ.

Contents

ํฌ์ŠคํŒ… ์ฃผ์†Œ๋ฅผ ๋ณต์‚ฌํ–ˆ์Šต๋‹ˆ๋‹ค

์ด ๊ธ€์ด ๋„์›€์ด ๋˜์—ˆ๋‹ค๋ฉด ๊ณต๊ฐ ๋ถ€ํƒ๋“œ๋ฆฝ๋‹ˆ๋‹ค.