๐Ÿ—‚๏ธ 2024.08.07 TIL

Donghyunยท2024๋…„ 8์›” 7์ผ
0

TIL (Today I Learned)

๋ชฉ๋ก ๋ณด๊ธฐ
29/53
post-thumbnail

Python

์˜ค๋Š˜์€ ๋ฆฌ์ŠคํŠธ์—์„œ ๊ฐ ์š”์†Œ๋“ค์—๋Œ€ํ•ด ๋ฐ˜๋ณต๋ฌธ์„ ๋Œ๋ฉด์„œ ๋”•์…”๋„ˆ๋ฆฌ์˜ ๊ฐ’์„ ๋ฆฌ์ŠคํŠธ ํ˜•ํƒœ๋กœ ์ €์žฅํ•˜๋Š” ๋ฐฉ๋ฒ•์„ ๋ฐฐ์› ๋‹ค.

  • ๋จผ์ €, {key: [ ]} ํ˜•ํƒœ๋กœ ๊ฐ’์ด ๋น„์–ด์žˆ๋Š” ๋”•์…”๋„ˆ๋ฆฌ๋ฅผ ๋งŒ๋“ค์–ด๋†“๊ณ 
  • for ๋ฌธ์„ ๋Œ๋ฉด์„œ ๋ฆฌ์ŠคํŠธ์— append ํ•˜๋Š”๊ฒƒ์ฒ˜๋Ÿผ dictionary[key].append(value) ๋ฅผ ํ•˜๋ฉด ๊ฐ’์„ ๋ฆฌ์ŠคํŠธ ํ˜•ํƒœ๋กœ ์ €์žฅํ•  ์ˆ˜ ์žˆ๋‹ค.
# ๋นˆ ๋ฆฌ์ŠคํŠธ๋ฅผ ๊ฐ’์œผ๋กœ ๊ฐ€์ง€๋Š” ๋”•์…”๋„ˆ๋ฆฌ ์ƒ์„ฑ
my_dict = {'a': [], 'b': [], 'c': []}

# ์ถ”๊ฐ€ํ•  ๊ฐ’๋“ค
values = [1, 2, 3, 4, 5]

# ๊ฐ ํ‚ค์— ๊ฐ’์„ ์ˆœ์ฐจ์ ์œผ๋กœ ๋ถ„๋ฐฐํ•˜์—ฌ ์ €์žฅ
keys = list(my_dict.keys())
for i, value in enumerate(values):
    my_dict[keys[i % len(keys)]].append(value)

# ๊ฒฐ๊ณผ ์ถœ๋ ฅ
print(my_dict)

# ๊ฒฐ๊ณผ
{'a': [1, 4], 'b': [2, 5], 'c': [3]}

๊ทธ๋ฆฌ๊ณ  ๋”•์…”๋„ˆ๋ฆฌ์˜ ๊ฐ’์„ 1์”ฉ ์˜ฌ๋ฆฌ๋Š” ๊ฒƒ๋„ ๊ฐ€๋Šฅ

# ์ดˆ๊ธฐ ๋”•์…”๋„ˆ๋ฆฌ
my_dict = {'a': 1, 'b': 2, 'c': 3}

# ๊ฐ ๊ฐ’์„ +1 ํ•˜๊ธฐ
for key in my_dict:
    my_dict[key] += 1

# ๊ฒฐ๊ณผ
{'a': 2, 'b': 3, 'c': 4}
profile
๋ฐ์ดํ„ฐ๋ถ„์„ ๊ณต๋ถ€ ์ผ๊ธฐ~!

0๊ฐœ์˜ ๋Œ“๊ธ€