python3字符串处理,高效切片

版权声明:本文为博主原创文章,但部分内容来源自互联网,大家可以随意转载,点赞或留言均可! https://blog.csdn.net/csdn_kou/article/details/83902378

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

切片

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))

猜你喜欢

转载自blog.csdn.net/csdn_kou/article/details/83902378