str.isdigit()
if int(a) == a:
pass
if isintace(a, int): #True로 값이 나오면 조건문 실행
pass
x = 10.0
float(x).is_integer() #True반환
if x % 1 == 0:
x**(1/2)
string.upper()#대문자로
string = string.lower()#소문자로
밑에 형식처럼 해야지만 적용이 된다.
a = ['a', 'b', 'c', 'd', '1', '2', '3']
result1 = "".join(a) #abcd123출력
print(result1)
리스트에 있는 요소들을 합쳐서 문자열로 반환하는 함수
'구분자'.join(리스트) #_이러한 구분자를 넣어서 반환함 a_b_c_d_1_2_3
my_string.split(" ")
str.replace('a','b')#a를 b로 바꾸기
str = str.replace('a','b')
이렇게 실행하면 str이 자동으로 바꿔지지 않으므로 꼭 밑에줄 형식으로 적어야 함
from functools import reduce
reduce(lambda x, y: x + y, [0, 1, 2, 3, 4]) #10
(lambda x,y: x + y)(10, 20) #30
result1 = sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(result1) # 출력 : 55
if search_string in main_string:
~~~
if search_string not in main_string:
~~~
if main_string.find(search_string) != -1:
print("검색 문자열이 메인 문자열에 포함되어 있습니다.")
len(str1)
s = '가나다라 마바사아 자차카타 파하'
s.startswith('가') #True
s.endswith('마') #False
' apple'.lstrip() # 인자가 없을 경우 왼쪽 공백 제거 'apple'
'apple '.rstrip() # 인자가 없을 경우 오른쪽 공백 제거 'apple'
' apple '.strip() # 인자가 없을 경우 왼쪽 공백 제거 'apple'
'apple'.strip('ae') # 양쪽끝에 a, e의 문자열의 모든 조합을 제거'ppl'
# a 리스트에서 10의 위치 찾기. (최소값인 1이 출력)
a = [11,10,12,13,20,31,11,10,10,11]
print(a.index(10)) # 1
# a 문자열에 1번째 ~ 6번째 위치에서 '1' 이라는 문자 위치 찾기
a = '123451'
print(a.index('1',1,6)) # 5
char = 'A'
result = ord(char)
print('유니코드 값:', result) #유니코드 값: 65
list.sort()
sorted(list)
a1 = [6, 3, 9]
a2 = a1.sort()
print(a1) # [3,6,9] 출력
print(a2) # sort함수의 리턴값은 none이므로 none으로 출력됨
b1 = [6, 3, 9]
b2 = sorted(b1)
print(b1) #[6,3,9] 원래대로 출력됨
print(b2) #[3,6,9]
b = eval("100 + 32") # 132 출력
s = 'coffee'
n = 5
result1 = f'저는 {s}를 좋아합니다. 하루 {n}잔 마셔요.'
print(result1) # 저는 coffee를 좋아합니다. 하루 5잔 마셔요.
from collections import Counter
sample4 = ["a","a","b","b","b","b","c"]
cnt = Counter(sample4).most_common()
print("cnt: " + str(cnt))
dict(cnt)
aa = {'0': 'AA', '1': 'BB', '2': 'CC'}
aa.get('2') # 결과: 'CC'
[k for k, v in aa.items() if v == 'CC' # 결과: ['2']
bb = {v:k for k,v in aa.items()} # {'AA': '0', 'BB': '1', 'CC': '2'}
bb.get('CC') # 결과: '2'
import math
numbers = [1, 2, 3, 4, 5]
print(math.prod(numbers)) # 120
print(math.factorial(5)) # 120
#틀린예시
arr = [0, 1]
list(set(arr)) = list(set(arr)).append(-1)
print(unique_arr) # None출력
#맞는 예시
arr = [0, 1]
unique_arr = list(set(arr)) # 중복 제거 후 리스트로 변환
unique_arr.append(-1)
print(unique_arr) # [0,1,-1]
>>> format(42, 'b') #이진수- 앞에 0b빼고 출력
'101010'
>>> format(42, 'o')
'52'
>>> format(42, 'x')
'2a'
>>> format(42, 'X')
'2A'
>>> format(42, 'd')
'42'
>>> format(42, '#b') #이진수- 앞에 0b 넣어서 출력
'0b101010'
>>> format(42, '#o')
'0o52'
>>> format(42, '#x')
'0x2a'
>>> format(42, '#X')
'0X2A'
>>> int('0b101010', 2)
42
>>> int('0o52', 8)
42
>>> int('0x2a', 16)
42
def solution(n, k):
word=""
while n:
word = str(n%k)+word
n=n//k
print(word)
answer.sort(key=len)
str은 remove없으므로, replace("s","")이런식으로 해야됨
lstrip, rstrip, split
s1 = s.lstrip('{').rstrip('}').split('},{')
젤 왼쪽{{ 지우고 젤 오른쪽 }} 지우고 분리함
for i,value in enumerate(['kim','lee','park','choi']):
print(i,value, end = " ")
0 kim 1 lee 2 park 3 choi 이 출력됨
priorities: [2, 1, 3, 2] 일 때,
queue = [(i,p) for i,p in enumerate(priorities)]
=> [(0, 2), (1, 1), (2, 3), (3, 2)]
>>> any([False, True, False])
True
>>> all([False, True, False])
False
cur = 3
temp = [1,3,6,2]
if any(cur<num for num in temp):
print("There exist number that is larger than 3")
from itertools import permutations
arr = ['a','b','c']
list(permutations(arr))
출력=>
[('a', 'b', 'c'),
('a', 'c', 'b'),
('b', 'a', 'c'),
('b', 'c', 'a'),
('c', 'a', 'b'),
('c', 'b', 'a')] 이렇게 모든 조합이 나온다.
만약 이차원 배열이라면?
arr = [[80,20],[50,40],[30,10]] 일때,
from itertools import permutations
for i in permutations(arr,len(arr)):
print(i)
=>
([80, 20], [50, 40], [30, 10])
([80, 20], [30, 10], [50, 40])
([50, 40], [80, 20], [30, 10])
([50, 40], [30, 10], [80, 20])
([30, 10], [80, 20], [50, 40])
([30, 10], [50, 40], [80, 20]) 이렇게 나온다.
from itertools import permutations
temper = [1,2,3]
for i in range(len(temper)):
temps+=list(permutations(temper, i+1))
print(temps)
이렇게 하면 출력 결과가 [(1,), (2,), (3,), (1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2), (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)] 이렇게 나오는데 이거를 num = [(''.join(t)) for t in temp] 해주면 1,2,3,12,13 ... 이런식으로 join돼서 결과가 나온다.
from itertools import combinations
arr = ['A', 'B', 'C']
nCr = itertools.combinations(arr, 2)
print(list(nCr))
결과 : [('A', 'B'), ('A', 'C'), ('B', 'C')] 이렇게 조합도 가능하다.
알파벳과 아스키코드와의 상관관계
A = 65
a = 97임
dictionary에 value를 0으로 모두 초기화하기
{'L': 1, 'i': 2, 'f': 1, 'e': 3, ' ': 6, 's': 2, 't': 3, 'o': 5, 'h': 2, 'r': 1, ',': 1, 'Y': 1, 'u': 1, 'n': 2, 'd': 1, 'p': 1, 'y': 1, '.': 1}
이런식으로 dictionary를 만들때
딕셔너리 d의 키에 해당 문자가 없다면 그 문자를 키로 등록하고 값은 0으로 초기화하는 방어적인 코드를 다음과 같이 사용했다.
if c not in d:
d[c] = 0
이렇게 코드를 안하면 해당 키값이 없는 상태에서 += 연산을 수행하므로 다음과 같은 KeyError 오류가 발생한다.
그럴때, 쓸수 있는 방법이 default dict이다.
from collections import defaultdict
text = "Life is too short, You need python."
d = defaultdict(int)
for c in text:
d[c] += 1
print(dict(d))
출력값: {'L': 1, 'i': 2, 'f': 1, 'e': 3, ' ': 6, 's': 2, 't': 3, 'o': 5, 'h': 2, 'r': 1, ',': 1, 'Y': 1, 'u': 1, 'n': 2, 'd': 1, 'p': 1, 'y': 1, '.': 1}
import math
math.ceil(-3.14) #결과는 -3
math.ceil(3.14) #결과는 4
import math
math.floor(3.14) #결과는 3
math.floor(-3.14) #결과는 -4
round(3.1415) #결과는 3
for key, element in example_dictionary.items():
print(key,element)
print(sorted(dic)) # ['classic','pop','trot'] 출력됨
print(sorted(dic, reverse=True))
print(sorted(dic.items())) # [('classic',1450),('pop',3100),('trot',620)]
# value 값을 기준으로 오름차순 정렬하여 (k, v) 리스트 반환
print(sorted(dic.items(), key=lambda x:x[1]))
# 위 값을 딕셔너리로 변환
print(dict(sorted(dic.items(), key=lambda x:x[1])))
# value 값을 기준으로 오름차순 정렬
print(sorted(dic,key=lambda x:dic[x]))
출력값:
[('trot',620), ('classic',1450),('pop',3100)]
{'trot':620, 'classic':1450, 'pop':3100}
['trot','classic','pop']
중요한거 순서대로 거꾸로! 정렬해주면
num_list = [('IMG', 12, 'img12.png'), ('IMG', 10, 'img10.png'), ('IMG', 2, 'img02.png'), ('IMG', 1, 'img1.png'), ('IMG', 1, 'IMG01.GIF'), ('IMG', 2, 'img2.JPG')]
name_list.sort(key=lambda i: i[1])
name_list.sort(key=lambda i: i[0])
print(name_list)
실행해주면 출력으로
[('IMG', 1, 'img1.png'), ('IMG', 1, 'IMG01.GIF'), ('IMG', 2, 'img02.png'), ('IMG', 2, 'img2.JPG'), ('IMG', 10, 'img10.png'), ('IMG', 12, 'img12.png')]
>> hangeuls = "가나다라마바사아자차카타파하"
>> hangeuls.find('사')
6
>> hangeuls.find('가')
0
>> hangeuls.find('사', 7)
-1
l_list.sort(key=lambda x:x*3, reverse=True)
이런식으로 lambda를 활용한 sort공부할 것 !!
tri = [[1, 2, 3], [4, 5], [6, 7, 8]]
flat_list = sum(tri, [])
출력결과는 flat_list는 [1, 2, 3, 4, 5, 6, 7, 8] 이렇게 된다.
sum(tri, []): 리스트의 리스트를 평탄화하는 방법으로, 초기값을 빈 리스트로 설정하고 리스트의 각 하위 리스트를 순차적으로 더함.