Python 기본 기능을 복습하자!
# Indexing 인덱싱
f="abcdefghijklmnopqrstuvwxyz"
f[1] # b
# Slicing 슬라이싱
f[4:15] # efghijklmno From f[4] to f[15]
split()
email = 'abc@abc.com'
domain = email.split('@)[1] # abc.com
domain = email.split('@)[1].split('.')[0] # abc
len()
append()
or an operatora = [1, 2, 3]
a.append(4) # a = [1, 2, 3, 4]
a += 5 # a = [1, 2, 3, 4, 5]
sort()
a = [2, 5, 3]
a.sort()
print(a) # [2, 3, 5]
a.sort(reverse=True)
print(a) # [5, 3, 2]
in
a = [2, 1, 4, "2", 6]
print(1 in a) # True
print("1" in a) # False
print(0 not in a) # True
dict = {'key':'someKey', value: 0}
dict = {}
or dict = dict()
in
to dermine if a key is in the dict (returns Boolean)if
executes code if Trueif
is False, use elif
to execute code if Trueif
and elif
are False, execute else
if condition == True :
print("if executed")
elif condition2 == True:
print("if is False, elif executed")
else:
print("if and elif are False, else executed")
fruits = ['사과', '배', '감', '귤']
for fruit in fruits:
print(fruit)
(index, value)
for index, value in enumerate(list):
print(index,value)
def funcName(input):
()
, as opposed to list []
a = [1,2,3,4,5,3,4,2,1,2,4,2,3,1,4,1,5,1]
a_set = set(a)
print(a_set) # {1,2,3,4,5}
# Intersection, union, and difference using sets
a = ['사과','감','수박','참외','딸기']
b = ['사과','멜론','청포도','토마토','참외']
a = set(a)
b = set(b)
print(a & b) # 교집합 Intersection
print(a | b) # 합집합 Union
print(a - b) # 차집합 Difference
f
in front of '
to create a f-string# Without f-string
print(name+'는 '+score+'점 입니다')
# With f-string
print(f'{name}은 {score}점입니다')
try:
function()
# if function() throws an error, except is executed
except:
print('Error')
If there is a Python file in the same directory and you would like to use its functions, use: from diffFile import *
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 '청소년'
# Run every index in 'people' with function 'check_adult' with map
# then print map in a list
result = map(check_adult,people)
# Change function check_adult into lambda form
result = map(lambda person: ('성인' if person['age'] > 20 else '청소년'), people)
print(list(result))
#Filter is similar to map, but picks values that are True
result = filter(lambda person: person['age'] > 20, people)