Python—隨筆記

Python—隨筆記

列表解析

根據已有列表,高效創建新列表的方式。
列表解析是Python迭代機制的一種應用,它常用於實現創建新的列表,因此用在[]中。

  [expression for iter_val in iterable]
  [expression for iter_val in iterable if cond_expr]
from pythonds.basic.stack import Stack

def parChecker(symbolString):
    s = Stack()
    balanced = True
    index = 0
    while index < len(symbolString) and balanced:
        symbol = symbolString[index]
        if symbol in "([{":
            s.push(symbol)
        else:
            if s.isEmpty():
                balanced = False
            else:
                top = s.pop()
                if not matches(top,symbol):
                       balanced = False
        for i in range(s.size()):
            print(s.items[i],end='')               
        # print([s.items[i] for i in range(s.size())])
        index = index + 1
    if balanced and s.isEmpty():
        return True
    else:
        return False

def matches(open,close):
    opens = "([{"
    closers = ")]}"
    return opens.index(open) == closers.index(close)

print(parChecker('{{([][])}()}'))
print(parChecker('[{)(]'))
from pythonds.basic.stack import Stack

def parChecker(symbolString):
    s = Stack()
    balanced = True
    index = 0
    while index < len(symbolString) and balanced:
        symbol = symbolString[index]
        if symbol in "([{":
            s.push(symbol)
        else:
            if s.isEmpty():
                balanced = False
            else:
                top = s.pop()
                if not matches(top,symbol):
                       balanced = False             
        print([s.items[i] for i in range(s.size())])
        index = index + 1
    if balanced and s.isEmpty():
        return True
    else:
        return False

def matches(open,close):
    opens = "([{"
    closers = ")]}"
    return opens.index(open) == closers.index(close)


print(parChecker('{{([][])}()}'))
print(parChecker('[{)(]'))

上述代碼段可以看出列表解析的優勢
同時

print(s.items[i] for i in range(s.size()))
print([s.items[i] for i in range(s.size())])

是有很大區別的

實例展示

轉載地址:https://www.cnblogs.com/liu-shuai/p/6098227.html
要求:列出1~10所有數字的平方
1、普通方法:

>>> L = []
>>> for i in range(1,11):
...     L.append(i**2)
... 
>>> print(L)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

2、列表解析

>>>L = [ i**2 for i in range(1,11)]
>>> print(L)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

要求:列出1~10中大於等於4的數字的平方
1、普通方法:

>>> L = []
>>> for i in range(1,11):
...     if i >= 4:
...         L.append(i**2)
... 
>>> print(L)
[16, 25, 36, 49, 64, 81, 100]

2、列表解析

>>>L = [ i**2 for i in range(1,11) if i >= 4 ]
>>>print(L)
[16, 25, 36, 49, 64, 81, 100]

要求:列出1~10所有數字的平方除以2的值
1、普通方法

>>> L = []
>>> for i in range(1,11):
...     L.append(i**2/2)
... 
>>> print(L)
[0, 2, 4, 8, 12, 18, 24, 32, 40, 50]

2、列表解析

>>> L = [i**2/2 for i in range(1,11) ]
>>> print(L)
[0, 2, 4, 8, 12, 18, 24, 32, 40, 50]

要求:列出"/var/log"中所有已’.log’結尾的文件
1、普通方法

import os
file = []
for file in os.listdir('/var/log'):
     if file.endswith('.log'):
         file.append(file)
 
print(file)

>>>['anaconda.ifcfg.log', 'Xorg.0.log', 'anaconda.storage.log', 'Xorg.9.log', 'yum.log', 'anaconda.log', 'dracut.log', 'pm-powersave.log', 'anaconda.yum.log', 'wpa_supplicant.log', 'boot.log', 'spice-vdagent.log', 'anaconda.program.log']

2.列表解析

import os
file = [ file for file in os.listdir('/var/log') if file.endswith('.log') ]
print(file)

>>>
['anaconda.ifcfg.log', 'Xorg.0.log', 'anaconda.storage.log', 'Xorg.9.log', 'yum.log', 'anaconda.log', 'dracut.log', 'pm-powersave.log', 'anaconda.yum.log', 'wpa_supplicant.log', 'boot.log', 'spice-vdagent.log', 'anaconda.program.log']

要求:實現兩個列表中的元素逐一配對
1、普通方法:

L1 = ['x','y','z']
L2 = [1,2,3]      
L3 = []
for a in L1:
     for b in L2:
         L3.append((a,b)) 
print(L3)

>>>[('x', 1), ('x', 2), ('x', 3), ('y', 1), ('y', 2), ('y', 3), ('z', 1), ('z', 2), ('z', 3)]

2、列表解析:

L1 = ['x','y','z']
L2 = [1,2,3]
L3 = [ (a,b) for a in L1 for b in L2 ]
print(L3)

>>>[('x', 1), ('x', 2), ('x', 3), ('y', 1), ('y', 2), ('y', 3), ('z', 1), ('z', 2), ('z', 3)]

使用列表解析生成 9*9 乘法表

print('\n'.join([''.join(['%s*%s=%-2s '%(y,x,x*y)for y in range(1,x+1)])for x in range(1,10)]))
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章