๋ด์ผ๋ฐฐ์์บ ํ์์ Python ์๊ณ ๋ฆฌ์ฆ ๋ฌธ์ ๋ฅผ ํ๊ธฐ ์ํ ํ์ต ๊ณผ์ ์ธ ๊ธฐ์ด ๊ฐ๋ ๊ฐ์๋ฅผ ์ค๋ ์๊ฐํ๋ค
# ๋ฌธ์์ด ๋ณํ ํจ์ : str()
# ๋ฌธ์์ด -> ๋ฌธ์์ด ๋ฆฌ์คํธ : split()
myemail = 'abc@sparta.co'
domain = myemail.split('@')[1].split('.')[0]
print(domain)
# ๊ฒฐ๊ณผ
sparta
< ๋ฆฌ์คํธ >
# ์์ ์ถ๊ฐํ ๋
1) 1๊ฐ ์ถ๊ฐํ ๋
๋ฆฌ์คํธ.append(์์)
๋ฆฌ์คํธ.insert(์์น, ์์)
2) ์ฌ๋ฌ๊ฐ ์ถ๊ฐํ ๋
๋ฆฌ์คํธ.extend(๋ฆฌ์คํธ)
# ์์ ์ ๊ฑฐํ ๋
1) ์ธ๋ฑ์ค๋ก ์ ๊ฑฐํ ๋
del ๋ฆฌ์คํธ[์ธ๋ฑ์ค]
๋ฆฌ์คํธ.pop(์ธ๋ฑ์ค)
2) ๊ฐ์ผ๋ก ์ ๊ฑฐํ ๋
๋ฆฌ์คํธ.remove(๊ฐ)
# ๊ฐ ๋ด๋ถ์ ์๋์ง ํ์ธ
๊ฐ in ๋ฆฌ์คํธ
๊ฐ not in ๋ฆฌ์คํธ
# enumerate()
๋ฆฌ์คํธ์์ ํ์ฌ ์ธ๋ฑ์ค๊ฐ ๋ช๋ฒ์งธ์ธ์ง ํ์ธํ ๋
example_list = ['์์A', '์์B', '์์C']
for i,value in enumerate(example_list):
print(i, value)
# ๊ฒฐ๊ณผ
0 ์์A
1 ์์B
2 ์์C
# try - except ๊ตฌ๋ถ
try:
# ์์ธ๊ฐ ๋ฐ์ํ ๊ฐ๋ฅ์ฑ์ด ์๋ ์ฝ๋
except:
# ์์ธ๊ฐ ๋ฐ์ํ์๋ ์คํํ ์ฝ๋
- ์ฅ์
ํญ์ ๋์๊ฐ๋ ํ๋ก๊ทธ๋จ์ด ์ค๋ฅ๋ฅผ ๋ง๋ฌ์ ๋ ์ค์ง์์ด ์คํ๋๊ฒ ํด์ค๋ค
- ๋จ์
๋จ์ฉํ๋ค๋ฉด ๋ฌด์จ ์๋ฌ๊ฐ ๋ฌ๋์ง ๋ชจ๋ฅธ๋ค
# ํ์ผ ๋ถ๋ฌ์ค๊ธฐ
from ๋ชจ๋์ด๋ฆ import ๊ฐ์ ธ์ค๊ณ ์ถ์ ํจ์
# if ๋ฌธ ์ผํญ์ฐ์ฐ์
num = 3
result = "์ง์" if num%2 == 0 else "ํ์"
print(f"{num}์ {result}์
๋๋ค.")
# map
๋ฆฌ์คํธ์ ๋ชจ๋ ์์๋ฅผ ์กฐ์ํ๊ธฐ
people = [
{'name': 'bob', 'age': 20},
{'name': 'carry', 'age': 38},
{'name': 'john', 'age': 7},
{'name': 'smith', 'age': 17},
{'name': 'ben', 'age': 27},
{'name': 'bobby', 'age': 57},
{'name': 'red', 'age': 32},
{'name': 'queen', 'age': 25}
]
def check_adult(person):
if person['age'] > 20:
return '์ฑ์ธ'
else:
return '์ฒญ์๋
'
result = map(check_adult, people)
print(list(result))
# ๊ฒฐ๊ณผ
['์ฒญ์๋
', '์ฑ์ธ', '์ฒญ์๋
', '์ฒญ์๋
', '์ฑ์ธ', '์ฑ์ธ', '์ฑ์ธ', '์ฑ์ธ']
# lambda
result = map(lambda x: ('์ฑ์ธ' if x['age'] > 20 else '์ฒญ์๋
'), people)
print(list(result))
# ๊ฒฐ๊ณผ
['์ฒญ์๋
', '์ฑ์ธ', '์ฒญ์๋
', '์ฒญ์๋
', '์ฑ์ธ', '์ฑ์ธ', '์ฑ์ธ', '์ฑ์ธ']
# filter
๋ฆฌ์คํธ์ ๋ชจ๋ ์์ ์ค ํน๋ณํ ๊ฒ๋ง ๋ฝ๊ธฐ
result = filter(lambda x: x['age'] > 20, people)
print(list(result))
# ๊ฒฐ๊ณผ
[{'name': 'carry', 'age': 38}, {'name': 'ben', 'age': 27}, {'name': 'bobby', 'age': 57}, {'name': 'red', 'age': 32}, {'name': 'queen', 'age': 25}]
# ํด๋์ค ์ฌ์ฉ๋ฒ
๋งค๊ฐ๋ณ์๋ก self๋ฅผ ์จ์คํ self. ํ์์ผ๋ก ์์ฑ์ ์ ๊ทผํ๋ค
class Monster():
hp = 100
alive = True
def damage(self, attack):
self.hp = self.hp - attack
if self.hp < 0:
self.alive = False
def status_check(self):
if self.alive:
print('์ด์์๋ค')
else:
print('์ฃฝ์๋ค')
m = Monster()
m.damage(120)
m2 = Monster()
m2.damage(90)
m.status_check()
m2.status_check()
# ๊ฒฐ๊ณผ
์ฃฝ์๋ค
์ด์์๋ค
'Knowledge๐ฆข > Python' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| [Python] RFM ์ธ๊ทธ๋จผํ ์ด์ (0) | 2024.08.22 |
|---|---|
| [Python] ์์ดํ ๋ณ ์กฐํฉ ์ฐพ๊ธฐ, 2๊ฐ์ ํ ์ด๋ธ ํฉ์น๊ธฐโก๏ธ (0) | 2024.07.11 |
| [Python] ์นดํ ๊ณ ๋ฆฌ ๋ถ๋ฅํ๊ธฐโก๏ธ (0) | 2024.07.10 |
| [Python] ํ์ด์ฌ iterable ์ ๋ป (0) | 2024.05.08 |
| [Python] ํ์ด์ฌ ๊ธฐ์ด๋ฌธ๋ฒ ๋ณต์ต (0) | 2024.04.05 |