파이썬 문법 끄적끄적
파이썬 문법 끄적끄적
파이썬
String
1
2
3
4
5
s = "Hello World!"
s = s.split(" ") # ["Hello", "World!"]
s = s[1].replace("!","") # "World"
s = s.startswith("W") # True
List
1
2
3
list = []
list = [1,2,3]
list.append(4)
Tuple
1
t = (1,2,3) # Immutable
Dictionary
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
customer = {}
customer['name'] = 'junoh'
number_dictionary = {
1: [1, 2, 3],
2: [4, 5, 6],
3: [7],
4: [8, 9, 10, 11],
5: [12, 13, 14, 15]
}
number_count = {}
for index, numbers in number_dictionary.items():
number_count[index] = len(numbers)
# {1: 3, 2: 3, 3: 1, 4: 4, 5: 4}
for index, _ in number_dictionary.items():
print(index)
for index in number_dictionary.keys():
print(index)
for numbers in number_dictionary.values():
print(numbers)
Set
1
2
3
4
5
6
7
8
9
mySet = set([1,2,3,1,2,3]) #{1,2,3}
copied_set = mySet.copy() #value copy
copied_set.add(7) #{1,2,3,7}
new_numbers = [1, 2, 3, 4, 5]
copied_set.update(new_numbers) #{1,2,3,4,5,7}
for
1
2
3
4
5
6
7
# 방법 1
durations = []
for talk in talks
durations.append(talk['duration'])
# 방법 2
durations = [talk['duration'] for talk in talks]
1
print("{}세 : {}".format(age, result))
sort
1
2
3
corpus.sort(key=itemgetter(1), reverse=True)[:2]
sorted(corpus, key = itemgetter(1), reverse=True)[:2]
sorted(corpus, key = lambda x:x[1], reverse=True)[:2]
map (lambda)
1
top_tags = map(lambda x: x[0], top_tag_and_views)
filter (lambda)
1
long_books = filter(lambda row: int(row[3] > 250), reader)
First Class Function
1
2
3
4
5
6
7
8
9
def getFirst(a):
return a[0]
def dummyFunc(a):
return getFirst(a)
result = dummyFunc([1,2,3])
print(result) # 1
이 기사는 저작권자의
CC BY 4.0
라이센스를 따릅니다.