1.字符串’123’转换为123

1. 利用 str()

  1. def fun(s):
  2. res = 0
  3. for c in s:
  4. for num in range(10):
  5. if c == str(num):
  6. res = res * 10 + num
  7. print(res) # 123

2. 利用 int()

  1. int('123)

3. 利用 ord()

  1. def func(s):
  2. res = 0
  3. for c in s:
  4. res = res*10 + ord('c') - ord('0')

4. 利用 eval()

描述

eval() 函数用来执行一个字符串表达式,并返回表达式的值。

语法

以下是 eval() 方法的语法:
eval(expression[, globals[, locals]])

参数

  • expression — 表达式。
  • globals — 变量作用域,全局命名空间,如果被提供,则必须是一个字典对象。
  • locals — 变量作用域,局部命名空间,如果被提供,可以是任何映射对象。

    返回值

    返回表达式计算结果。
    1. def func(s):
    2. res = 0
    3. for c in s:
    4. res = res*10 + eval(f'{c}*1')
    5. return res # 123

    5.利用 reduce()

    1. res = reduce(lambda res, c: res * 10 + eval(f'{c}*1'), '123', 0) # 123
    2. res = reduce(lambda res,c: res*10 + ord(c) - ord('0'),'123',0) # 123

    2. python代码实现删除一个list里面的重复元素

    ```python def distFunc1(a): “””使用集合去重””” a = list(set(a)) print(a)

def distFunc2(a): “””将一个列表的数据取出放到另一个列表中,中间作判断””” list = [] for i in a: if i not in list: list.append(i)

  1. #如果需要排序的话用sort
  2. list.sort()
  3. print(list)

def distFunc3(a): “””使用字典””” b = {} b = b.fromkeys(a) c = list(b.keys()) print(c)

if name == “main“: a = [1,2,4,2,4,5,7,10,5,5,7,8,9,0,3] distFunc1(a) distFunc2(a) distFunc3(a)

<a name="jEU5Z"></a>
# 3. 输入日期,判断这一天是这一年的第几天
```python
import datetime
def dayofyear():
    year = input("请输入年份: ")
    month = input("请输入月份: ")
    day = input("请输入天: ")
    date1 = datetime.date(year=int(year),month=int(month),day=int(day))
    date2 = datetime.date(year=int(year),month=1,day=1)
    return (date1-date2).days+1
today = datetime.date.today()

origin = datetime.date(year=today.year, month=1, day=1)
res = (today - origin).days+1
print(f'{today} is the {res}th day in {today.year}.')
>>>2020-07-22 is the 204th day in 2020.
now = datetime.datetime.now()
pre = datetime.timedelta(days=0, hours=0, minutes=0, seconds=0)

print(f'It is been {(now-pre).minute+(now-pre).hour*60}mins today.')
>>>It is been 630 mins today.

4. 两个有序列表,l1,l2,对这两个列表进行合并不可使用extend

def func():
    global s1, s2
    print(s1, s2)
    res = []
    m, n = len(s1), len(s2)
    p1, p2 = 0, 0
    while p1 < m and p2 < n:    
        if s1[p1] > s2[p2]:
            res.append(s2[p2])
            p2 += 1
        else:
            res.append(s1[p1])
            p1 += 1
    while p1 < m:
        res.append(s1[p1])
        p1 += 1
    while p2 < n:
        res.append(s2[p2])
        p2 += 1
    print(f'res = {res}')
# 使用del
while len(s1)>0 and len(s2) > 0:
    if s1[0] > s2[0]:
        res.append(s1[0])
        del s1[0]
    else:
        res.append(s2[0])
        del s2[0]
while len(s1) > 0:
while len(s2) > 0:

5. 数组排序 偶数降序,奇数升序

def func():
    global s
    s.sort()
    l, r = 0, len(s)-1
    while l < r:
        while l < r and s[r] % 2 != 0:
            r -= 1
        while l < r and s[l] % 2 != 0:
            l += 1
        if l<r:
            s[l], s[r] = s[r], s[l]
            r -= 1
            l+=1
    print(s)

s = [1,2,3,6,110,23,38,291,29,485,382,24,18]
>>>[1, 382, 3, 110, 38, 23, 24, 29, 18, 6, 291, 2, 485]

6. 数组中第二大的数

def func():
    global s
    first, second = s[0], s[0]
    for it in s:
        if it > first:
            second = first
            first = it
        elif it > second:
            second = it
    print(f'first = {first}, second = {second}')

s = [1,2,3,6,110,23,38,291,29,485,382,24,18]
>>>first = 485, second = 382

>>>s.sort(reversed=True)[1]
>>>382
def func():
    global s
    from functools import reduce
    res = reduce(lambda tmp, x: tmp[1] < x and (tmp[1], x)
                                or tmp[0] < x and (x, tmp[1])
                                or tmp
                        , s, (0, 0))[0]

s = [1,2,3,6,110,23,38,291,29,485,382,24,18]
>>>382

7. lambda 与闭包

下面代码的输出是什么?

def func():
    return [lambda x : i*x for i in range(4)]
print([f(3) for f in func])

正确答案是[9,9,9,9],而不是[0,3,6,9]产生的原因是Python的闭包的后期绑定导致的,这意味着在闭包中的变量是在内部函数被调用的时候被查找的,
因为,最后函数被调用的时候,for循环已经完成, i 的值最后是3,因此每一个返回值的i都是3,所以最后的结果是[9,9,9,9]
我们查看函数中的lamdda是什么:

def func():
    l = [lambda x:x * i for i in range(4)]
    print(l)
func()
>>>
[<function func.<locals>.<listcomp>.<lambda> at 0x000001DD9A4A5AE8>, 
 <function func.<locals>.<listcomp>.<lambda> at 0x000001DD9A4A5B70>, 
 <function func.<locals>.<listcomp>.<lambda> at 0x000001DD9A4A5950>, 
 <function func.<locals>.<listcomp>.<lambda> at 0x000001DD9A4A5BF8>]

使用生成器获得[0, 3, 6, 9]的结果


def funb():
    for i in range(4):
        yield lambda x: i * x
print([m(3) for m in funb()])  # 0, 3, 6, 9

8. 手写计时装饰器

import time
import timeit

def decorator_timer(func):
    def wrapper(*args, **kwargs):
        t1 = time.time()
        c1 = time.clock()
        i1 = timeit.default_timer()
        func(*args, **kwargs)
        t2 = time.time()
        c2 = time.clock()
        i2 = timeit.default_timer()
        print(f'{func.__name__}() has been running for {round(t2-t1,6)}s time.time().')
        print(f'{func.__name__}() has been running for {round(c2-c1,6)}s time.clock().')
        print(f'{func.__name__}() has been running for {round(i2-i1,6)}s timeit.default_timer().')
        return func
    return wrapper


@decorator_timer
def foo():
    res = 0
    for i in range(1000000000):
        res += 1
    print(res)
    return res

foo()


#或者
def decorator_timer(funcname=''):
    def decorator(func):
        def wrapper(*arg, **kwargs):
            t1 = time.time()
            res = func(*arg, **kwargs)
            t2 = time.time()
            print(f'{func.__name__}() has been running for {round(t2-t1,3)}s.')
            return res
        return wrapper
    return decorator

@decorator_timer('xx')
def xx():
    pass
foo() has been running for 40.161075s time.time().
foo() has been running for 40.161019s time.clock().
foo() has been running for 40.161019s timeit.default_timer().

9. 一句话实现阶乘

reduce(lambda x,y : x*y,range(1,n+1))