iT邦幫忙

1

Python 中的 簡潔語法 - 1

本篇為觀看影片的統整 - 1
Yes

# print each
colors = ['red', 'green', 'blue']

example:
for i in range(colors):
    print(color[i])

better solution:
for color in colors:
    print(color)

# looping backwards
example:
for i in range(len(colors)-1, -1, -1):
    print colors[i]

better solution:
for color reverse(colors)
    print(color)

# looping with index
example:
for i in range(len(colors)):
    print i, '--->', colors[i]

better solution:
for i, color in enumerate(colors):
    print i, '--->', color
    
# looping over two collection
colors = ['red', 'green', 'blue']
name = ['raymond', 'rachal', 'matthew']

example:
n = min(len(names), len(colors))
for i in range(n):
    print names[i], '--->' colors[i]
    
better solution:
for name, color in zip(names, colors):
    print name '--->', color

# custom sort order
example:
def complare_length(c1, c2):
    if len(c1) < len(c2): return -1
    if len(c1) > len(c2): return 1
    return 0
print(sort(colors, cmp=compare_length))

better solution:
print(sort(colors, key=len))

# call function until a sentinel value
blocks = []

example:
while True:
    block = f.read(32)
    if block == '':
        break
    blocks.append(block)

better solution:    
## iter 可接收兩個參數,一個是被重複執行的函式,一個是終點的值 ##
for blocks in iter(partial(f.read, 32), ''):
    blocks.append(block)
    
# 多跳出點 in for loop
example:
def find(seq, target):
    found = False
    for i, value in enumerate(seq):
        if value == target:
            found = True
            break
    if not found:
        return -1
    return i

better solution:
def find(seq, target):
    for i, value in enumerate(seq):
        if value == target:
        break
    else:
        return -1
    return i

# Dictionary #

# looping over dictionary keys
d = {'aaa': 'green', 'bbb': 'blue', 'ccc': 'red'}

example:
for k in d.keys():
    if k.startswith('a'):
        del d[k]

better solution:        
d = {k : d[k] for k in d if not k.startswith('a') }

# looping over dictionary keys and values
example:
for k in d:
    print k, "--->", d[k] 
    
better solution:    
for k, v in d.items():
    print k, "--->", v

# Constrct a dictionary from pair
names = ['aaa', 'bbb', 'ccc']
colors = ['green', 'blue', 'red']

k = dict(zip(names, colors))

# Counting with dictionaries
colors = ['green', 'blue', 'red', 'blue', 'green']
result = {'green': 2, 'blue': 2, 'red': 1}

example:
d = {}
for color in colors:
    if color not in d:
        d[color] = 0
    d[color] += 1
 
better solution:   
d = {}
for color in colors:
    d[color] = d.get(color, 0) + 1

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言