최초 발행일 2020-05-25
//javascript
var arr = [1];
arr[1] = 2; // arr는 [1, 2]
#python
arr = [1]
arr[1] = 2 #IndexError: list assignment index out of range
#파이썬에서는 append 메서드로 배열에 순차적으로 엘리먼트를 추가해야한다
arr.append(2) # arr [1, 2]
a = 10
b = 20
result = (a-b) if a == b else (a+b) # 결과는 a+b = 30
a = [1, 2, 3]
for idx, val in enumerate(a):
print(idx, val)
"""
0 1
1 2
2 3
"""
count = 0
# count++ -> 런타임에러
count += 1
isdigit()이 있다.'2'.isdigit() #True
'*'.isdigit() #False
eval("2 * 3") # 6
eval("10-3") # 7
eval("2" + "*" + "3" + "-" + "2") # 4
a = [1, 2]
b = a
c = [1, 2]
a is b # True
a is c # False
a == c # True
ord('a') #97
chr(97) # 'a'
파이썬 숫자를 소수점 2자리에서 반올림을 하고 싶으면 round 함수를 사용하면된다.
round(10.123, 2) #10.12
round(10.126, 2) #10.13
하지만 round 함수는 끝자리가 0이라면 출력을 하지 않는다.
round(300/3, 2) # 100.0
round(100.00, 2) # 100.0
이럴 때는 format 함수를 사용하여 숫자 서식을 지정할 수 있다. 폭은 필드영역의 공백 수를 결정하고, 소수점 정밀도는 소수점 아래 표현할 숫자의 수를 결정한다.폭은 정수 부분만을 지칭하는 것이 아닌, 소수점 아래 표현된 숫자들까지 지칭한다.
format(item, 폭(width).소수점정밀도(precision)f)
format(round(100.00, 2), ".2f") #100.00
format(round(100.127, 2), ".2f") # 100.13
`math` 모듈을 사용한다.
import math #math 모듈을 먼저 import해야 한다.
math.ceil(-1.11) #결과는 -1
math.ceil(1.11) #결과는 2
>>> import math
>>> math.floor(1.11) #결과는 1
>>> math.floor(-1.11) #결과는 -2
print 함수를 사용할때 마지막 인자로 sep='!'를 줘서 출력하고자 하는 것들의 사이마다 !를 추가해서 출력되게 할 수 있다.
print(1, 2, 3, 4, sep="!") # 1!2!3!4
zip 함수는 다음과 같이 두 개 이상의 배열에 대해 각 배열의 같은 인덱스끼리 그룹핑을 해준다.
>>> for e in zip([1, 2, 3], [4, 5, 6]):
... print(e)
...
(1, 4)
(2, 5)
(3, 6)
>>> for e in zip([1, 2, 3], [4, 5, 6], [7, 8, 9]):
... print(e)
...
(1, 4, 7)
(2, 5, 8)
(3, 6, 9)
zip의 인자로 들어간 배열중 길이가 더 긴 배열의 엘리먼트는 무시된다.
>>> for e in zip([1, 2, 3], [4, 5, 6, 7]):
... print(e)
...
(1, 4)
(2, 5)
(3, 6)
isinstance([], list) #True
isinstance(1, list) # False
chr = 'asdf'
''.join(list(reversed(chr))) #fdsa
import json
def sort_by_price_ascending(json_string):
input = json.loads(json_string)
result = sorted(input, key=lambda obj: (obj["price"], obj['name']))
return json.dumps(result)
sort_by_price_ascending('[{"name":"eggs","price":1},{"name":"coffee","price":1.5},{"name":"rice","price":4.04} ,{"name":"aoffee","price":1.5}]')
# output
# '[{"name": "eggs", "price": 1}, {"name": "aoffee", "price": 1.5}, {"name": "coffee", "price": 1.5}, {"name": "rice", "price": 4.04}]'
예시 위와 동일