# Python 5 個技巧
來源 : https://www.youtube.com/watch?v=C-gEQdGVXbk&t=1779s
[TOC]
## I. Number
```python=
num1 = 10_000_000
num2 = 1_000_010
print(num1 + num2)
# Output : 11000010
total = num1 + num2
print(f'{total:,}')
# Output : 11,000,010
```
## II. With Open
```python=
with open('test.txt', 'r') as f:
file_contents = f.read()
words = file_contents.split(' ')
word_count = len(words)
print(word_count)
```
## III. Enumerate, Zip
```python=
# Method I
names = ['Perer Parker', 'Clark Kent', 'Wade Wilson']
heroes = ['Spiderman', 'Superman', 'Deadpool']
for index, name in enumerate(names):
hero = heroes[index]
print(f'{name} is actually {hero}')
# Method II
names = ['Perer Parker', 'Clark Kent', 'Wade Wilson']
heroes = ['Spiderman', 'Superman', 'Deadpool']
for name, hero in zip(names, heroes): # 這裡也能多加list進來,例如zip(names, heroes, universes)
print(f'{name} is actually {hero}')
# Output :
# Perer Parker is actually Spiderman
# Clark Kent is actually Superman
# Wade Wilson is actually Deadpool
```
## IV. Unpacking
```python=
a, b, c = [1, 2, 3]
# a, b, c = (1, 2, 3)
print(a)
print(b)
a, b, c, *_, d = [1, 2, 3, 4, 5, 6]
print(a)
print(b)
print(d)
# Output :
# 1
# 2
# 6
```
## V. Setattr (Class)
```python=
# Method I
class Person():
pass
person = Person()
person.first = "Courey"
person.last = "Schafer"
print(person.first)
print(person.last)
# Method II
# class A(object):
# bar = 1
# a = A()
# getattr(a, 'bar') # 獲得bar值
# # Output : 1
# setattr(a, 'bar', 5) # 設定bar值
# a.bar
# # Output : 5
class Person():
pass
person = Person()
person_info = {'first': 'Corey', 'last': 'Schafer'}
for key, value in person_info.items():
setattr(person, key, value)
for key in person_info.keys():
print(getattr(person, key))
```