In [1]:
# List, Dict
animals = ["강아지", "고양이", "참새", "이구아나", "부엉이"]
my_informations = {
"name": "kkp",
"phonenumber": "010623533XX",
"email": "kimkipoy26@gmail.com",
"age": 29,
}
In [2]:
for animal in animals:
print(animal)
In [3]:
for my_information in my_informations:
print(my_information)
In [4]:
for my_information in my_informations:
print(my_informations[my_information])
In [6]:
my_informations["name"]
Out[6]:
In [7]:
for i in range(len(animals)):
if i == 2:
animals[i] = "파이썬"
print(animals[i])
In [8]:
animals.index("강아지")
Out[8]:
In [9]:
for animal in animals:
index = animals.index(animal)
if index == 2:
animals[index] = "참새"
print(animals[index])
In [11]:
for index, _ in enumerate(animals):
if index == 2:
animals[index] = "파이썬"
print(animals[index])
enumerate는 tuple로만 가능. index와 다르게 전체를 다 훑는다. 멈추지 않는다. 열거하다라는 의미.
In [12]:
for index, value in enumerate(animals):
if value == "강아지":
animals[index] = "이구아나"
print(animals[index])
In [13]:
words = ('cool', 'powerful', 'readable')
for i in range(len(words)):
print((i, words[i]))
In [14]:
for i, item in enumerate(words):
print((i, item))
In [16]:
d = {'a': 1, 'b': 1.2, 'c': 1j}
d.items()
Out[16]:
In [17]:
for key, val in sorted(d.items()):
print('Key: %s has value: %s' % (key, val))
In [18]:
for item in sorted(d.items()):
print('item:', str(item))
In [19]:
%%timeit
y = [i*2 for i in range(10000)]
In [20]:
%%timeit
x = range(10000)
y = []
for i in x:
y.append(i * 2)
In [4]:
def is_prime(number): #2부터 number-1 까지의 숫자로 각각 나누어서 체크해본다.
for i in range(2, number):
if (number % i == 0):
return False # 소수가 아니다
return True # 소수가 맞으니 나온다.
is_prime(5)
Out[4]:
In [5]:
def get_prime_numbers(number):
prime_numbers = [] # 빈 리스트 하나 만들어서
for i in range(2, number+1): # 소수인지 아닌지를 체크하는 함수
if is_prime(i):
prime_numbers.append(i)
return prime_numbers
In [6]:
get_prime_numbers(50)
Out[6]:
In [11]:
def is_prime_optimized(number):
for i in range(2, int(number**0.5)+1):
if(number % i == 0):
return False
return True
In [12]:
def get_prime_numbers_optimized(number):
prime_numbers = []
for i in range(2, number):
if is_prime_optimized(i):
prime_numbers.append(i)
return prime_numbers
In [13]:
get_prime_numbers_optimized(50)
Out[13]:
In [14]:
import time
In [15]:
start_time = time.time()
get_prime_numbers(20000)
end_time = time.time()
end_time - start_time
Out[15]:
In [16]:
start_time = time.time()
get_prime_numbers_optimized(20000)
end_time = time.time()
end_time - start_time
Out[16]:
In [17]:
def sum(a, b):
return a + b #print는 출력만. return은 결과를 다른 사람들이 쓸 수 있음
In [18]:
result = sum(1, 3)
In [19]:
result
Out[19]:
In [20]:
print(sum(1,3))
In [21]:
def sum(a, b):
print("sum: {result}".format(result = a + b))
In [22]:
sum(10, 20)
In [23]:
result = sum(2, 3)
In [24]:
result
sum => Function
a, b => Parameter. 매개변수. 외부로부터 받아들이는 임의값. 함수 선언
10, 20 => Argument. 인수. 함수 호출시의 인수
In [30]:
def sum(number_list):
total = 0
for number in number_list:
total += number
return total
In [31]:
sum({1,2,3,4})
Out[31]:
In [33]:
def sum(*args):
total = 0
for arg in args:
total += arg
return total
In [34]:
sum(1,2,3,4) # *args 변수명 => * 튜플 형태로 바로 받겠다.
Out[34]:
In [35]:
sum({1,2,3})
In [36]:
def greeting(name, course):
print("{name}님 {course} 등록을 축하드립니다.".format(name=name, course=course))
In [37]:
values = ("김기표", "데사스") # Tuple 형태
In [38]:
greeting(values)
In [39]:
greeting(*values) # unpack / unpacking
In [40]:
greeting("김기표", "데사스")
In [41]:
def greeting(name, reason, course):
print("{name}님 {course} 등록한 이유는 {reason}".format(name=name, course=course, reason=reason))
In [42]:
values = ("김기표", "배우고 싶어서", "데사스")
In [43]:
greeting(*values)
unmaed => *args(tuple)
named => **kwargs(dict)을 unpacking한다고 생각. kwargs - keyward arguments
In [44]:
def greeting(name, course):
print("{name}님 {course} 등록을 축하드립니다.".format(name=name, course=course))
In [45]:
greeting(name="kkp", course="dss")
In [46]:
values = {"name": "김기표", "course": "데사스"}
In [47]:
greeting(**values)
In [48]:
greeting(*values)
In [49]:
def print_all_informations(**kwargs):
for key, value in kwargs.items():
print("{key} => {value}".format(key=key, value=value))
In [50]:
informations = {"name": "김기표", "email": "kkp@gmail.com", "phonenumber": "010~"}
In [51]:
print_all_informations(**informations)
In [52]:
print_all_informations(name = "김기표", course="데사스")
In [ ]:
In [53]:
def increment(x):
return x + 1
In [54]:
increment(55) # 이렇게 쓸 거면 뭐하러 만들어?
Out[54]:
In [55]:
increment_lambda = lambda x: x + 1
In [56]:
increment_lambda(33) # 이 방법 또한 함수와 마찬가지
Out[56]:
In [57]:
(lambda x: x + 1)(33) # 함수 굳이 안 만들고 여기에서만 쓰겠다.
Out[57]:
In [58]:
(lambda x, y: x**y)(7,6) # 데이터 전처리 등 한 줄로 처리하는 것이 좋을 때
Out[58]:
In [60]:
def square(numbers):
square_list = []
for number in numbers:
square_list.append(number**2)
return square_list
In [61]:
square([1,2,3,4])
Out[61]:
In [62]:
def square(x):
return x**2
In [63]:
list(map(square, [1,2,3]))
Out[63]:
In [64]:
list(map(lambda x: x**2, [1,2,3]))
Out[64]:
In [65]:
map(square, [1, 2, 3])
Out[65]:
In [66]:
list([1, 4, 9])
Out[66]:
In [68]:
numbers = [1,2,3,4,5,6,7,8,9,10]
In [69]:
list(filter(lambda x: x>5, numbers))
Out[69]:
In [70]:
a = map(lambda x: x**8, [1, 2, 3])
In [71]:
list(a)
Out[71]:
In [72]:
a
Out[72]:
In [73]:
import time
def sleeping_numbers(x):
time.sleep(1)
return x**2
In [74]:
sleeping_numbers(3)
Out[74]:
In [75]:
a = map(sleeping_numbers, [5, 6, 7, 8, 0])
In [76]:
for i in a:
print(i)
In [78]:
list(a)
Out[78]:
map => 모든 elements에 대해 새로운 List
Filter => 모든 elements => True인 elements만 새로운 List
Reduce. 줄여서 하나만 남긴다.
In [80]:
import functools
In [81]:
functools.reduce(lambda x, y: x+y, [10, 20, 30, 40])
Out[81]:
In [83]:
def sum(x, y):
print((x, y))
return x + y
In [84]:
functools.reduce(sum, [10, 20, 30, 40, 50])
Out[84]:
In [85]:
def max(numbers):
max_number = numbers[0]
for number in numbers:
if number > max_number:
max_number = number
return max_number
In [86]:
max([23,45,63,34,57])
Out[86]:
In [87]:
functools.reduce(lambda x, y: x if x>y else y, [23,45,63,34,57])
Out[87]:
[참일 때의 값] if [조건문] else [거짓 일 때의 값]
In [88]:
3 if True else 5
Out[88]:
In [89]:
3 if False else 5
Out[89]:
In [92]:
awsome_list = [1, 2, "김기표", {}, [], 5, 3]
In [91]:
isinstance(3, int) # 숫자만 맞으면 True
Out[91]:
In [93]:
list(map(lambda x: x**2,
filter(lambda x: isinstance(x, int), awsome_list)))
Out[93]:
In [94]:
[i for i in range(10)]
Out[94]:
In [95]:
list(map(lambda x: x**2, range(10)))
Out[95]:
In [96]:
[i**2 for i in range(10)]
Out[96]:
In [97]:
[i**2 for i in range(10) if i**2 > 50]
Out[97]:
1 - 100까지 숫자 중에서 짝수인 것들만 제곱하는 리스트
In [98]:
[i**2 for i in range(1, 100+1) if i%2 == 0]
Out[98]:
In [100]:
len([i**2 for i in range(1, 100+1) if i%2 == 0])
Out[100]:
In [101]:
list(map(lambda x: x**2, filter(lambda x: x % 2 == 0, range(1, 100+1))))
Out[101]:
In [98]:
list(map(lambda x: x**2, filter(lambda x: x % 2 == 0, range(100+1))))
Out[98]:
In [102]:
len(list(map(lambda x: x**2, filter(lambda x: x % 2 == 0, range(1, 100+1)))))
Out[102]:
In [103]:
awsome_list = [i for i in range(0, 9+1)]
In [104]:
awsome_list
Out[104]:
In [105]:
a = map(lambda x: x**2, filter(lambda x: x>5, awsome_list))
In [106]:
list(a)
Out[106]:
In [107]:
[i**2 for i in range(0, 9+1) if i > 5]
Out[107]:
In [109]:
MAX = 1000
not_prime_list = [
i
for i in range(2, int(MAX**0.5)+1)
]
print(not_prime_list)
In [112]:
MAX = 1000
not_prime_list = [
j
for i in range(2, int(MAX**0.5)+1)
for j in range(i*2, MAX+1, i)
]
prime_list = [
i
for i in range(2, MAX+1)
if i not in not_prime_list
]
print(prime_list), len(prime_list)
Out[112]: