1. 程式人生 > >python3字串處理,高效切片

python3字串處理,高效切片

高階技巧:切片,迭代,列表,生成器

切片

L = ['Hello', 'World', '!']


print("-------1.一個一個取-------")
print(L[0])
print(L[1])
print(L[2])


print("-------2.開闢一個新列表把內容存進去-------")
r = []
for i in range(3):
    r.append(L[i])

print(r)


print("-------3.切片操作-------")
print("L[0:3]", L[0:3])
print("L[:3]", L[:3])
print("L[1:3]", L[1:3])
print("L[-1]", L[-1])
print("L[-2:]", L[-2:])
print("L[-2:-1]", L[-2:-1])


print("_____________切片操作詳解——————————————————————")
L = list(range(1, 100))
print(L)

print(L[:10])
print(L[5:10])
print(L[-10])
print(L[-10:])
print(L[:-80])
print(L[10:-80])


print("前10個數每隔2個取一個")
print(L[::])
print(L[:10:2])
print("所有數每隔5個取一個")
print(L[::5])

print("一個例題,把字串前後的空格刪除")
def trim(s):
    length = len(s) - 1
    if length < 0:
        return ''
    last = length
    while s[ length ] == ' ' :
        length -= 1
        last = length
        if length < 0:
            return ''
    first = 0
    while s[first] == ' ':
        first += 1
    last += 1
    l = s[first:last]
    return l


if trim('hello  ') != 'hello':
    print('測試失敗!')
elif trim('  hello') != 'hello':
    print('測試失敗!')
elif trim('  hello  ') != 'hello':
    print('測試失敗!')
elif trim('  hello  world  ') != 'hello  world':
    print('測試失敗!')
elif trim('    ') != '':
    print('測試失敗!')
elif trim('') != '':
    print('測試失敗!')
else:
    print('測試成功!')


print("一個例題,查詢最大數,最小數")
def findMinAndMax(L):
    if len(L) == 0:
        return None, None

    max, min = L[0], L[0]

    for i in L:
        if min > i:
            min = i
        if max < i:
            max = i

    return min, max


if findMinAndMax([]) != (None, None):
    print('測試失敗!')
elif findMinAndMax([7]) != (7, 7):
    print('測試失敗!')
elif findMinAndMax([7, 1]) != (1, 7):
    print('測試失敗!')
elif findMinAndMax([7, 1, 3, 9, 5]) != (1, 9):
    print('測試失敗!')
else:
    print('測試成功!')
  • 切片的幾個例子
def trim(s):
    length = len(s) - 1
    if length < 0:
        return ''
    last = length
    while s[ length ] == ' ' :
        length -= 1
        last = length
        if length < 0:
            return ''
    first = 0
    while s[first] == ' ':
        first += 1
    last += 1
    l = s[first:last]
    return l


if trim('hello  ') != 'hello':
    print('測試失敗!')
elif trim('  hello') != 'hello':
    print('測試失敗!')
elif trim('  hello  ') != 'hello':
    print('測試失敗!')
elif trim('  hello  world  ') != 'hello  world':
    print('測試失敗!')
elif trim('    ') != '':
    print('測試失敗!')
elif trim('') != '':
    print('測試失敗!')
else:
    print('測試成功!')



def findMinAndMax(L):
    if len(L) == 0:
        return None, None

    max, min = L[0], L[0]

    for i in L:
        if min > i:
            min = i
        if max < i:
            max = i

    return min, max


if findMinAndMax([]) != (None, None):
    print('測試失敗!')
elif findMinAndMax([7]) != (7, 7):
    print('測試失敗!')
elif findMinAndMax([7, 1]) != (1, 7):
    print('測試失敗!')
elif findMinAndMax([7, 1, 3, 9, 5]) != (1, 9):
    print('測試失敗!')
else:
    print('測試成功!')



print("一個例題,取出字元,並全部轉換為小寫")

L1 = ['Hello', 'World', 18, 'Apple', None]
L2 = [s.lower() for s in L if isinstance(s, str)]
print(L2)

# 測試:
print(L2)
if L2 == ['hello', 'world', 'apple']:
    print('測試通過!')
else:
    print('測試失敗!')

生成器

生成器詳解

g = (x * x for x in range(1, 10))

for i in g:
    print(i)

  • 生成器特點
print(
      "generator的函式,在每次呼叫next()的時候執行,"
      "遇到yield語句返回,再次執行時從上次返回的yield語句"
      "處繼續執行。"
      )

def odd():
    print('step 1')
    yield 1
    print('step 2')
    yield(3)
    print('step 3')
    yield(5)


o = odd()
print(next(o))
print(next(o))
print(next(o))

  • 應用:列印楊輝三角
print("----------------------------------------------------")
print("楊輝三角列印")

def triangles():
    L = [1]
    while True:
        yield L
        L = [1] + [L[i - 1] + L[i] for i in range(1, len(L))] + [1]

n = 0
results = []
for t in triangles():
    print(t)
    results.append(t)
    n = n + 1
    if n == 10:
        break

用filter求素數

計算素數的一個方法是埃氏篩法,它的演算法理解起來非常簡單:

首先,列出從2開始的所有自然數,構造一個序列:

2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, …

取序列的第一個數2,它一定是素數,然後用2把序列的2的倍數篩掉:

3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, …

取新序列的第一個數3,它一定是素數,然後用3把序列的3的倍數篩掉:

5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, …

取新序列的第一個數5,然後用5把序列的5的倍數篩掉:

7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, …

不斷篩下去,就可以得到所有的素數。

用Python來實現這個演算法,可以先構造一個從3開始的奇數序列:

def _odd_iter():
    n = 1
    while True:
        n = n + 2
        yield n

注意這是一個生成器,並且是一個無限序列。

然後定義一個篩選函式:

def _not_divisible(n):
    return lambda x: x % n > 0
最後,定義一個生成器,不斷返回下一個素數:

def primes():
    yield 2
    it = _odd_iter() # 初始序列
    while True:
        n = next(it) # 返回序列的第一個數
        yield n
        it = filter(_not_divisible(n), it) # 構造新序列

這個生成器先返回第一個素數2,然後,利用filter()不斷產生篩選後的新的序列。

由於primes()也是一個無限序列,所以呼叫時需要設定一個退出迴圈的條件:

# 列印1000以內的素數:

for n in primes():
    if n < 1000:
        print(n)
    else:
        break

注意到Iterator是惰性計算的序列,所以我們可以用Python表示“全體自然數”,“全體素數”這樣的序列,而程式碼非常簡潔。

特殊函式

  • 傳入函式
def add(x, y, f):
    return f(x) + f(y)

x = -5
y = 6
f = abs

print(add(x, y, f))
  • map

def f(x):
    return x * x
r = list(map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9]))

print(r)

輸出結果

[1, 4, 9, 16, 25, 36, 49, 64, 81]

Process finished with exit code 0
  • reduce
from functools import reduce

def mul(x, y):
    return x * y
def prod(L):
    return reduce(mul, [1, 3, 5, 7, 9])

print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
if prod([3, 5, 7, 9]) == 945:
    print('測試成功!')
else:
    print('測試失敗!')
  • 一個應用
    字串轉整形
print("字串轉整形")
from functools import reduce
def fn(x, y):
    return x * 10 + y

def char2num(s):
    digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
    return digits[s]

L = reduce(fn, map(char2num, '13579'))
print(isinstance(L,int))