Get the App
SLTechnology News&Howtos  ›  Development  › 

How python handles data types efficiently

Shulou Source: shulou.com Published: 2022-06-01 04:26:37 11月05日 Update

Editor to share with you how python efficient handling of data types, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to understand it!

Efficient methods for handling data types:

Processing data

In [1]: from random import randintIn [2]: data= [randint (- 10Magne10) for _ in range (10)] In [3]: dataOut [3]: [- 3,-4, 3, 4, 7,-2,-4, 1, 7,-9] # filter negative numbers In [9]: list (lambda (lambda x filter)) Out [9]: [3,4,7,1] 7] [for x in data if x > = 0] # list generation method [x for x in data if x > = 0] # which is faster and list parsing is faster than iterative In [15]:% timeit [x for x in data if x > = 0] 581 ns ±23.8 ns per loop (mean ±std. Dev. Of 7 runs, 1000000 loops each) In [16]:% timeit filter (lambda x loops each > = 0Magna data) 237 ns ±4 ns per loop (mean ±std. Dev. Of 7 runs, 1000000 loops each) # get 20 students' scores d = {x:randint (60100) for x in range (1Magne21)} # Dictionary formula, iteritems iterate dictionary at the same time, # # get students with scores greater than 90 {if v for if v > 90} # set parsing In [35]: {x for x in s if x% 3 = = 0} Out [35]: {- 9,-3,3} # name each element in the meta-ancestor Improve program readability # small meta-ancestor storage space, fast access speed # define constant NAME = 0AGE=1SEX=2EMAIL=3# unpacking usage, define enumeration types similar to other languages That is to define the numerical constant NAME,AGE,SEX,EMAIL=range (4) # case student= ('Jim',16,'male','jin@163.com') # nameprint (student [0]) # ageprint (student [1]) # can be optimized to print (student [name]) print (student [age]) # namedtuple is a subclass inherited from tuple, namedtuple and tuple have cooler features # namedtuple creates an object similar to tuple, and the object has accessible properties. This object is more like a class with data properties, but the data properties are read-only. From collections import namedtupleStudent = namedtuple ('Student', [' name','age','sex','email']) s=Student ('Jim',16,'male','jim@163.com') the frequency of the occurrence of elements in the s.name s.age# statistical sequence from random import randintdata= [randint (0Lab 20) for _ in range (30)] # create a dictionary {0lg0 1c=dict.fromkeys.} # method 0) In [52]: for x in data:...: C [x] + = resume method 2 Statistical word Frequency from collections import Counterc2=Counter (data) # talk about the constructor of sequence input to Counter Get the dictionary that the Counter object is the frequency of elements # use most_common to count the word frequency In [58]: c2.most_common (3) Out [58]: [(10,4), (20,3), (8,3)] # Statistics English composition word frequency import retxt=open ('emmmm.txt'). Read () # is assigned to Counterc3=Counter (re.split ('\ W') after segmentation Txt)) # find the 10 most frequently used words c3.most_common (10) # built-in functions are run at c speed For example, sortedfrom random import randint d = {x:randint (60100) for x in 'xyzabc'} # {' asides: 91, 'baked: 65,' cations: 76,'x: 85,'y: 84,'z: 72} # sorted (d) In [15]: zip (d.values (), d.keys ()) Out [15]: In [16]: list (d.values (), d.keys ()) Out [16]: [(68,'x') (70,'y'), (77,'z'), (72,'a'), (65,'b'), (69,'c')] # quickly find the public key in multiple dictionaries # In [1]: from random import randint,sampleIn [2]: sample ('abcdefg',3) Out [2]: [' Out, 'averse,' b'] In [4]: sample ('abcdefg') Randint (3Magazine 6)) Out [4]: ['baked,' ajar,'d'] In [5]: S1 = {x:randint (1) for x in sample ('abcdefg',randint (3))} In [9]: s1Out [9]: {' x:randint: 1, 'baked: 2,' cations: 3, 'fallow: 3,' gallows: 3} In [10]: S1 = {x:randint (1) for x in sample ('abcdefg') Randint (3Magazine 6)} In [11]: s1Out [11]: {'baked: 2,' d é cet: 3, 'gathers: 3} In [12]: s1Out [12]: {' baked: 2, 'dumped: 3,' gallows: 3} In [13]: S2 = {x:randint (1prime4) for x in sample ('abcdefg',randint (3pyr6))} In [15]: S3 = {x:randint (1pm 4) for x in sample (' abcdefg') Randint (3d6)} # for Loop traversal method Find kIn [19]: res= [] In [20]: for k in S1:...: if k in S2 and k in S3:...: res.append (k...:).: In [21]: resOut [21]: ['b'] # through the keys () method of the dictionary Find three dictionaries of the same keyIn [26]: s1.keys () & s2.keys () & s3.keys () Out [26]: {'b'} # get an iterator object # In [27]: map (dict.keys, [s1jcms3]) Out [27]: In [28]: list (map (dict.keys, [s1jms3])) Out [28]: [dict_keys (['glossy,' dancer,'b']) Dict_keys (['glossy,' averse, 'caged,' baked,'f']), dict_keys (['dashed,' faded, 'baked,' cached, 'eyed,' a'])] # the same result was taken out by reduce In [30]: from functools import reduceIn [31]: reduce (lambda acharge bregued aformaiture map (dict.keys, [S1 Persons2) S3]) Out [31]: {'b'} # such that from time import timefrom random import randintfrom collections import OrderedDictd=OrderedDict () players = list ("ABCDEFGH") start=time () for i in range (8): input () p=players.pop (randint) end=time () print D [k]) # View user history function, deque of standard library collections Double-ended circular queue, stored in the content Pickle is stored in the file from random import randintfrom collections import dequeN = randint (0100) history = deque ([] 5) def guess (K): if K = = N: print ('correct') return True if K < N: print ('% s is less-than n% K) else: print ("% s is greater-than N"% K) return Falsewhile True: line = input ("Please enter a number:") if line.isdigit (): k=int (line) history.append (k) if guess (k): break elif line = = 'history' Or line = 'hackers: print (list (history)) these are all the contents of the article "how python handles data types efficiently" Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Dictionary data object method type processing statistics element content attribute constant article word frequency iteration classmate sequence faster speed frequency meta-ancestor Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi Microsoft Redmi vpn OPPO Reno