Bactoria 황준오

파이썬 문법 끄적끄적

2019-07-09
bactoria

파이썬

String

s = "Hello World!"

s = s.split(" ") # ["Hello", "World!"]
s = s[1].replace("!","") # "World"
s = s.startswith("W") # True

List

list = []
list = [1,2,3]
list.append(4)

 

Tuple

t = (1,2,3) # Immutable

 

Dictionary

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

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
durations = []
for talk in talks
    durations.append(talk['duration'])

# 방법 2
durations = [talk['duration'] for talk in talks]

print

print("{}세 : {}".format(age, result))

 

sort

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)

top_tags = map(lambda x: x[0], top_tag_and_views)

 

filter (lambda)

long_books = filter(lambda row: int(row[3] > 250), reader)

 

First Class Function

def getFirst(a):
    return a[0]
    
def dummyFunc(a):
    return getFirst(a)
    
result = dummyFunc([1,2,3])

print(result) # 1

황준오 (Bactoria) 황준오 (Bactoria)

.

Comments

Content