Discover core python applications programming, include the articles, news, trends, analysis and practical advice about core python applications programming on alibabacloud.com
Random#产生随机集合Def randomset ():s = Set (")N = Random.randint (1,10)For I in Range (N):S.add (Random.randint (0,9))return sA = Randomset ()B = Randomset ()Print A, b#print a| B,ab# A = set ()# B = set ()# A.add (1)# A.add (2)# B.add (2)# Print a| B,ab#对输入进行处理, go [], Save as Collection#要考虑输入为空集的处理#输入格式为 [], turn into ', then set (')def input_to_set (S1):Set1 = set ()If S1! = ' [] ':U1,U2 = S1.split (' [')U1,U3 = U2.split ('] ')List1 = U1.split (', ')For I in List1:j = Int (i) #列表中单独字符串转换为数字Set1.a
Python does not compel you to program in an object-oriented way (unlike Java)#Coding=utf8classFooclass (object): Version= 0.1def __init__(Self, nm='John Doe'): Self.name=nmPrint('Created A class instance for', NM)defShowName (self):Print('Your name is', Self.name)Print('My name is', self.__class__.__name__) defshower (self):Print(self.version)defAddme2me (self, x):return(x +x) foo1=Fooclass () foo1.showname ( )Print(Foo1.shower ())Print(Foo1.addme2
, there is the existence of Gil Lock, Python can only have one thread to operate the same operation at the same timeImportThreading fromQueueImportQueueImportCopyImport TimedefJob (L, Q): Res=sum (L) q.put (res)defMultithreading (L): Q=Queue () Threads= [] forIinchRange (4): T= Threading. Thread (Target=job, args= (Copy.copy (L), q), name='t%i'%i) T.start () threads.append (t) [T.join () forTinchThreads] Total=0 for_inchRange (4): Total+=Q.get ()P
Chapter Fourth Python objects1. Type is also an object:A = 4;type (a)->2.python2.2 start, class and type unification, class = Type, instance is object of type3. Any object has a natural Boolean value4. integer objects, string objects , tuple objects are immutable objects, Python efficiently caches integers and string objects , so a=3;b=1+2; (A is B) returns True, If the float type returns false. The cache r
numbers, ranging from large to small. (b) is the same as a, but it is arranged in a dictionary order from large to small. " # (a) Defget_num (): globalnum_listnum_list= []num= ' whilenum!= '! ': num=raw_input (' Enter some numbers to '! "End"). Strip () ifnum!= '! ': try: num=float (num) except: print ' input is wrong, please re-enter ' get_num () else: num_list.append (num) else: breakreturnnum_listdefsort_descending (): get_num () printsorted (num_list,reverse=true) print '---------------
difference is that the list can be changed, and tuples cannot be changed.4-9 Exercise, given the following assignment:A = tenB = TenC =d =e = 10.0f = 10.0what is the output of the following expressions?Why? In Python, integer and string objects are non-mutable objects, and Python caches them very efficiently, causing us to think that Python should create new obj
Chapter One Welcome to Python world1 Python Features:Advanced interpretive language for system invocationObject orientedUpgradeable, extensible, portedAutomatic Memory Manager (memory management is the responsibility of the Python interpreter)2 installationWindows is installed only by downloading an installation package from the official web site and then steppin
string containing Unicode characters to a fully Unicode string object. The Unicode operator must appear before the original string operator5. Built-in functionsCMP (): As with the comparison operator, the built-in CMP () function is also compared against the ASCII value of the string.Len (): The built-in function Len () returns the number of characters in a string.max () and Min (): for string types they work well and return the maximum or minimum characters, arranged in ASCII values.Enumerate
: = Fp.readlines () for in data: Print(re.sub ( '\[email protected] (\w+.?) +"[email protected]', line). Rstrip ())Results:27. Extract the month, day, and year from the timestamp and then format "Month, day, year".Importref= Open ('Redata.txt','R') with open ('Path\redata2.txt','R') as Fp:data=Fp.readlines () forLineinchdata:m= Re.match ('^\w{3}\s (\w{3}) \s{1,2} (\d{1,2}) \s\d{2}:\d{2}:\d{2}\s (\d{4})', line)Print('%s,%s,%s'% (M.group (1), M.group (2), M.group (3)))Results:Pytho
In the case of variable names only, the output string is enclosed in single quotation marks. This is so that non-string objects may also appear on the screen as characters.The print function prints out the value of the variable.Print is called by the Str () method. The Repr () method is called when only the variable name is used.Proof:-------------------------------------------Class MyClass:def __repr__ (self):return "repr";def __str__ (self):return "STR";# The function called when testing print
parameter sizhint represents the maximum word size returned.Output:1. Write (): writes a string containing text data or binary data blocks to a file. 2, Writelines (): For the list operation, accept a list of strings as parameters, write them to the file, the line terminator is not automatically added, if necessary, you must call the Writelines method before the end of each line to add a terminator. When reading rows from a file using read () or readlines (),
)):.. print a,>>1 2 3 4 5 6 7 8 9>>print ' Hello%d%d\...%s '%[1,2, ' Helloword ' *100]>>hello12helloword .....>>for i in range (0,1,2):... print I,>>0 1 2>>for I, J in Enumerate (a):... print I,j>>0 1>>1 2>>, .....13. List parsing>>p=[x for x in range (10)]>>p>>[1,2,3,4,5,6,7,8,9,10]>>p=[x for x in range (ten) if not x%2]>>p>>[0,2,4,6,8]14. File Operation:TryFile=open (' E://log.txt ', ' R ') #默认打开方式为读, W for write, A for appendFor line in File.readlines (): #for the line in file:Print line,Exce
- Isfile () specifies whether the path exists and is a file + Islink () specifies whether the path exists and is a symbolic link - Ismount () specifies whether the path exists and is a mount point +Samefile () Two path names pointing to the same file4. File related modules1Base64 provides the encoding between the binary string and the text stringdecoding Operation2BINASCII provides the encoding between binary and ASCII encoded binary stringsdecoding Operation3 BZ2A Accessing compressed files in
you specify a key, the key must be a A The sort () method that is used to compare the callback function. -Reversed (SEQ) c takes a sequence as a parameter, returning an iterator that is accessed in reverse order (PEP 322) - Sorted (ITER, theFunc=None, -key=None, -Reverse=False) c takes an iterative object as an argument, returns an ordered list; optional parameters - the meaning of Func,key and reverse is the same as the parameter meaning of the List.sort () built-in function. + Sample. -SUM (s
Seventh chapter mapping and aggregation capabilitiesA dictionary (the only mapping type in Python)1 basicCreate and assign values:Normal creation: >>>dict = {' name ': ' Earth ', ' Port ': 80}Use the Factory function Dict () to create:>>> fdict = Dict ([' X ', 1], [' Y ', 2])>>> fdict{' Y ': 2, ' X ': 1}Use Fromkeys () to create a default dictionary:>>> ddict = {}.fromkeys (' x ', ' Y '),-1)>>> ddict{' Y ':-1, ' X ':-1}>>> edict = {}.fromkeys (' foo '
1, install Python, this has nothing to say, directly installed on the line2, do parallel computing, data mining, machine learning and so on generally need to use numpy, this in the Windows version installed a bit of a problem, installation is more troublesome, it is recommended to build the environment on Linux3, install Openmpi, (not very good installed) This online at present there is no better shortcut installation method, generally download the so
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.