1.1. How to filter data according to conditions in lists
# 1.1.How to filter data according to conditions in lists data = [-1, 2, 3, -4, 5] #Screen out data Data larger than or equal to zero in the list #The first method is not recommended. res1 = [] for x in data: if x >= 0: res1.append(x) print(res1) #The second is list parsing, which is recommended. res2 = [ x for x in data if x >= 0] print(res2) #Third uses filter function res3 = list(filter(lambda x : x>= 0,data)) print(res3)
1.2. How to filter data according to conditions in dictionaries
# 1.2.How to filter data according to conditions in dictionaries from random import randint #Creating Students'Dictionary,The student number is 1.~20,The score is 50.~100 random d = {'student%d'% i: randint(50,100) for i in range(1,21)} print(d) #Filter out the student dictionary with a score of 90 #The first method d1 = {k:v for k,v in d.items() if v >= 90} print(d1) #The second method d2 = dict(filter(lambda item:item[1] >= 90, d.items())) print(d2)
1.3. How to filter data according to conditions in a set
# 1.3.How to filter data according to conditions in a set from random import randint s = {randint(0,20) for _ in range(20)} print(s) #Screen out the number that can be divided by three s1 = {x for x in s if x % 3 == 0} print(s1)
1.4. How to name each element in the meta-ancestor to improve program readability
The following are the ancestors who use functions to determine age and sex, but the code is poor readability. Others do not know what student[1] and student[2] mean. How to solve it?
def func(student): if student[1] < 18 : pass if student[2] == 'male': pass student = ('derek',22,'male','111@qq.com') func(student)
Solution 1: Define enumeration types
#1.4..How to Name Every Element in Yuanzu to Improve Program Readability def func(student): if student[1] < 18 : pass if student[2] == 'male': pass s1 = ('derek',22,'male','111@qq.com') #First: Use enumerations from enum import IntEnum class StudentEnum(IntEnum): NAME = 0 AGE = 1 SEX = 2 EMAIL = 3 print(s1[StudentEnum.NAME]) print(s1[StudentEnum.AGE])
Solution 2: Replace the built-in tuple with collections.namedtuple in the standard library
#1.4..How to Name Every Element in Yuanzu to Improve Program Readability def func(student): if student[1] < 18 : pass if student[2] == 'male': pass s1 = ('derek',22,'male','111@qq.com') #First: Use enumerations from enum import IntEnum class StudentEnum(IntEnum): NAME = 0 AGE = 1 SEX = 2 EMAIL = 3 print(s1[StudentEnum.NAME]) print(s1[StudentEnum.AGE]) #The second is using standard libraries collections.namedtuple Substitute built in tuple from collections import namedtuple Student = namedtuple('student',['name','age','sex','email']) s2 = Student('derek',22,'male','222@qq.com') print(s2[0]) #derek # Can pass s2.name Get name print(s2.name) #derek
1.5. How to sort the items in the dictionary according to the size of the median value in the dictionary
The first method: list parsing
# 1.5.How to sort the items in a dictionary according to the size of the median value in the dictionary from random import randint d = {k: randint(60, 100) for k in 'abcdefg'} print(d) #The first method: use list parsing or zip()function,Dictionary keys and values Reverse list1 = [(v,k) for k,v in d.items()] #Or use zip()function # list2 = list(zip(d.values(),d.keys())) print(list1) list1 = sorted(list1,reverse=True) print(list1)
The second uses sorted
# 1.5.How to sort the items in a dictionary according to the size of the median value in the dictionary from random import randint d = {k: randint(60, 100) for k in 'abcdefg'} print(d) #The first method: use list parsing or zip()function,Dictionary keys and values Reverse list1 = [(v,k) for k,v in d.items()] #Or use zip()function # list2 = list(zip(d.values(),d.keys())) list1 = sorted(list1,reverse=True) #The second method is to use sorted sort p = sorted(d.items(),key=lambda item:item[1],reverse=True) print(p) #[('a', 97), ('b', 93), ('d', 93), ('e', 92), ('f', 76), ('c', 66), ('g', 61)] #Add a ranking to the score d = {k:(i,v) for i, (k,v) in enumerate(p,1)} print(d) #{'g': (1, 97), 'd': (2, 92), 'f': (3, 91), 'c': (4, 79), 'a': (5, 78), 'e': (6, 67), 'b': (7, 64)}
1.6. How to Statistics the Frequency of Elements in Sequences
# 1.6 How to Statistics the Frequency of Elements in Sequences from random import randint from collections import Counter data = [randint(1,5) for _ in range(1,20)] print(data) #[5, 2, 1, 2, 5, 3, 1, 1, 1, 4, 2, 5, 3, 2, 3, 5, 1, 2, 5] #The highest frequency of calculation is three numbers. c = Counter(data) print(c.most_common(3)) #[(1, 5), (3, 4), (2, 4)]
1.7. How to quickly find common keys in multiple dictionaries
# 1.7.How to quickly find common keys in multiple dictionaries from random import randint,sample from functools import reduce d1 = {k:randint(1,4) for k in sample('abcdefgh',randint(3,6))} d2 = {k:randint(1,4) for k in sample('abcdefgh',randint(3,6))} d3 = {k:randint(1,4) for k in sample('abcdefgh',randint(3,6))} #1.Dictionary-using keys()Method, get a dictionary keys Set #2.Use map Function, get each dictionary keys Set #3.Use reduce,Take all dictionaries keys Intersection of sets dl = [d1,d2,d3] #Find the same in three dictionaries keys result = reduce(lambda a,b: a & b, map(dict.keys, dl)) print(result)
1.8. How to keep dictionaries in order
# 1.8.How to keep dictionaries in order from collections import OrderedDict from itertools import islice d = OrderedDict() d['e'] = 5 d['d'] = 4 d['c'] = 3 d['b'] = 2 d['a'] = 1 print(d) #OrderedDict([('e', 5), ('d', 4), ('c', 3), ('b', 2), ('a', 1)]) #OrderedDict Dictionary, which maintains the order in which elements are inserted during iteration def query_by_order(d, a, b =None): if b is None: b = a + 1 return list(islice(d,a,b)) #Fifth key res1 = query_by_order(d,4) print(res1) #['a'] #Second and third key res2 = query_by_order(d,1,3) print(res2) #['d', 'c']
1.9. How to Realize User's History Recording Function
Use queues with capacity n to store history
- Use deque double-ended circular queue to store history (deque is saved in memory, and the next boot history will disappear)
- If you want to save it to your hard disk, use the pickle module so that you can start using it next time.
# 1.9 How to Realize User's History Recording Function from random import randint from collections import deque import pickle def guess(n, k): if n == k: print('Guess right. That's the number.%d' % k) return True if n < k: print('Guess big, than%d Small' % k) elif n > k: print('Guess it's smaller than that.%d large' % k) return False def main(): n = randint(1, 100) i = 1 hq = deque([], 5) while True: line = input('[%d]Please enter a number:' % i) if line.isdigit(): k = int(line) hq.append(k) i += 1 if guess(n, k): break elif line == 'quit': break elif line == 'history': print(hq) if __name__ == '__main__': main() #Result [1]Please enter a number: 1 //Guess smaller, bigger than 1 [2]Please enter a number: 2 //Guess smaller, bigger than 2 [3]Please enter a number: 3 //Guess smaller, bigger than three. [4]Please enter a number: history deque([1, 2, 3], maxlen=5) [4]Please enter a number: