手动实现python里面的方法(16个)

1.	method in 
def is_in(char, string):
    for item in string:
        if item == char:
            return True
    return False
<<< print(is_in('a', 'ABC'))
... False

2.	method sorted()
def is_sorted(seq):
    for i in range(len(seq)-1):
        if seq[i] > seq[i+1]:
            return False
    return True
<<< print(is_sorted("acbde"))
... False

3.	method abs()
def abs(x):
    if x < 0:
        return -x
    return x
<<< print(abs(-2.75))
... 2.75

4.	method all()
def all(lst):
    for item in lst:
        if not bool(item):
            return False
    return True
<<< print(all([1, -4, "cat", [[]]]))
... True
<<< print(all([1, -4, "cat", []]))
... False

5.	method any()
def any(lst):
    for item in lst:
        if bool(item):
            return True
    return False
<<< print (any([None, 0, "", -1]))
... True

6.	method max()
def max(lst):
    current_maxone = lst[0]
    for item in lst:
        if item > current_maxone:
            current_maxone = item
    return current_maxone
<<< print(max(['A', 'a', 'a']))
... 'a'(because'a' > 'A')

7.	method min()
def min(lst):
    current_min = lst[0]
    for item in lst:
        if item < current_min:
            current_min = item
    return current_min
<<< print(min(['A', 'a', 'a']))
... 'A'

8.	method reversed()
def reversed(seq):
	# method 1
    return list(reversed(seq))
	
	# method 2
    new_lst = []
    for i in range(len(seq)-1, -1, -1):
        new_lst.append(seq[i])
    return new_lst

9.	method sum()
def sum(lst):
    total = 0
    for item in lst:
        total += item
    return total

10.	method bin()-十进制转为二进制,(0b/-0b+x mod 2得到的余数从下往行上)
def bin(x):
    start = '0b'
    if x < 0:
        x = abs(x)
        start = '-0b'
    string = str(x % 2)
    x = x // 2
    while x > 0:
        string += str(x % 2)
        x = x // 2
    return start + string[::-1]

11.	method enumerate():【举个例子解释enumerate()】
a. 普通for-loop:
i = 0
seq = ['one', 'two', 'three']
for item in seq:
    print(i, item)
    i += 1
... 
0 one
1 two
2 three

b.enumerate():
for item in enumerate(seq):
    print(item)
...
(0, 'one')
(1, 'two')
(2, 'three')

for num, element in enumerate(seq):
    print(num, element)
...
0 one
1 two
2 three

手动实现method enumerate()def enumerate(seq, start=0):
    enum = []
    for i in range(len(seq)):
        enum.append((i+start, seq[i]))
    return enum
<<< print (enumerate(['cat', 'dog', 'horse'], 5))
... [(5, 'cat'), (6, 'dog'), (7, 'horse')]

12.	method filter():
def filter(function, seq):
    filter_list = []
    for item in seq:
        if function(item):
            filter_list.append(item)
    return filter_list
    
<<< def filter_a(x):
    	return x == 2
<<< print(filter(filter_a, [2, 2, 4, 5, 2]))
... [2, 2, 2]

13.	method map():
>>> map(square, [1,2,3,4,5])   # 计算列表各个元素的平方
... [1, 4, 9, 16, 25]
def map(function, seq):
    new_list = []
    for item in seq:
        new_list.append(function(item))
    return new_list

14. method range(start, stop, step)
def lim_range(start, stop, step=1):
    new_lst = []
    i = start
    if step > 0:
        while i < stop:
            new_lst.append(i)
            i += step
    else:
        while i > stop:
            new_lst.append(i)
            i -= step
    return new_lst

15. method round()
def round(number, ndigits=0):
#Remove all numbers but the last to be rounded using integer division
 #if ndigits=0, number//0.1, ndigits=1, number//0.01...
  #Check whether negative, and if so remove negative
    negative = number<0
    number = abs(number)/(10**(-(ndigits+1)))
    #Remove all extra digits
    number //= 1
    rounding = number%10
    if rounding > 5:
        number = number//10+1
    elif rounding < 5:
        number = number//10
    else:
        number = number//10
        if number%10 %2 ==1:
            number += 1
    #Shift number to correct decimal places
    number /= 10**ndigits
    if negative:
        number *= -1
    return number

16. method set()
<<< set('runoob')
...['b', 'r', 'u', 'o', 'n']
def set(aList):
    new_list = []
    for item in aList:
        if item not in new_list:
            new_list.append(item)
    return new_list

你可能感兴趣的:(python基础教程)