Iron python27_ Module Learning 2

Source: Internet
Author: User
Tags format definition local time month name python script

Most of the content was excerpted from the blog http://www.cnblogs.com/Eva-J/

Collections Module

On the basis of the built-in data type (DICT, list, set, tuple),
The collections module also provides several additional data types: Counter, deque, Defaultdict, Namedtuple, and Ordereddict.

1.namedtuple:
Generate a tuple that can use the name to access the content of the element;
2.deque:
Two-terminal queue, can quickly append and eject objects from the other side;
3.Counter: Counter, mainly used to count;
4.OrderedDict: Ordered dictionary;
5.defaultdict: A dictionary with default values.

Namedtuple

We know that a tuple can represent an immutable collection, for example, a two-dimensional coordinate of a point can be expressed as:

>>>P=(1,2) However, see (1,2, it is difficult to see that this tuple is used to represent a coordinate. At this point, Namedtuple came in handy: fromCollectionsImportNamedtuplepoint=Namedtuple (' point ', [' x ',' y ']) p=Point (1,2)Print(p.x)# 1Print(P.Y)# 2Print(p)# Point (X=1, y=2)Similarly, if you want to represent a circle with coordinates and radii, you can also define it with Namedtuple:#namedtuple (' name ', [Property list]):Circle=Namedtuple (' Circle ', [' x ',' y ',' R '] Deque when using the list to store data, accessing the elements by index is very fast, but inserting and deleting elements is very slow, because list is linear, and when the data is large, insertions and deletions are inefficient. Deque is a two-way list for efficient insert and delete operations, suitable for queues and stacks:>>>  fromCollectionsImportDeque>>>Q=Deque ([' A ',' B ',' C '])>>>Q.append (' x ')>>>Q.appendleft (' y ')>>>Qdeque ([' y ',' A ',' B ',' C ',' x '] Deque also supports Appendleft () and Popleft () in addition to the list's append () and pop (), which makes it very efficient to add or remove elements to the head. Ordereddict when using Dict, key is unordered. We cannot determine the order of key when we iterate over the dict. If you want to keep the key in order, you can use Ordereddict:>>>  fromCollectionsImportOrdereddict>>>D= Dict([(' A ',1), (' B ',2), (' C ',3)])>>>D# Dict's key is unordered.{' A ':1,' C ':3,' B ':2}>>>Od=Ordereddict ([(' A ',1), (' B ',2), (' C ',3)])>>>Od# Ordereddict's key is ordered.Ordereddict ([(' A ',1), (' B ',2), (' C ',3]) Note that ordereddict keys are sorted in the order in which they were inserted, not the key itself:>>>Od=Ordereddict ()>>>nd' Z ']= 1>>>nd' y ']= 2>>>nd' x ']= 3>>>Od.keys ()# returns in the order of the inserted key[' Z ',' y ',' x ']defaultdict has the following set of values [ One, A, -, -, -, the, the, the, About, -...], will be all greater than theValue is saved to the first key in the dictionary, which is less than theValue is saved to the value of the second key. That is: {' K1 ': Greater Than the,' K2 ': Less than theYou can save some code by using defaultdict: fromCollectionsImportDefaultdictvalues=[ One, A, -, -, -, the, the, the, About]my_dict=Defaultdict (List) forValueinchValuesifValue> the: my_dict[' K1 '].append (value)Else: my_dict[' K2 '].append (value)Print(my_dict)#defaultdict (<class ' list '), {' K2 ': [One, one, one, one, one, one, and one], ' K1 ': [[n], [[]]When using Dict, if the referenced key does not exist, the keyerror is thrown. The biggest advantage of the default dictionary is that you never get an error when you use key to obtain a value; The default dictionary is to set a default value for value in the dictionary. If you want the key to not exist, return a default value, you can use Defaultdict: fromCollectionsImportDefaultdictdd=Defaultdict (Lambda:' n /A ') dd[' Key1 ']= ' abc 'Print(dd[' Key1 '])# Key1 exists, return ' abc 'Print(dd[' Key2 '])# Key2 does not exist, returns the default value ' N/a 'The purpose of the Countercounter class is to track the number of occurrences of a value. It is an unordered container type, stored in the form of a dictionary key-value pair, where the element is counted as the key and its count as value. The count value can be any interger (including0and negative numbers). The counter class is similar to bags or multisets in other languages. fromCollectionsImportCounterc=Counter (' Abcdeabcdabcaba ')Print(c) Output: Counter ({' A ':5,' B ':4,' C ':3,' d ':2,' E ':1}) Counter class common operationssum(C.values ())# Total number of all countsC.clear ()# Reset the Counter object, note that it is not deletedList(c)# Convert keys in C to listSet(c)# Convert the keys in C to setDict(c)# Convert key-value pairs in C to dictionariesC.items ()# Convert to (Elem, CNT) format listCounter (Dict(List_of_pairs))# Convert list from (Elem, CNT) format to counter class objectC.most_common () [:-N:-1]# Remove n elements with a minimum countC+=Counter ()# Remove 0 and negative valuesCommon methods of Time module1.Time.sleep (secs) (thread) Delays the specified time run. Unit is seconds.2.Time.time () Gets the three ways in which the current timestamp represents time in Python, there are typically three ways to represent time: timestamp, tuple (struct_time), formatted time string: (1Timestamp (timestamp): Typically, a timestamp represents a1970Years1Month1Dayxx:xx:xxThe offset at which to start the calculation in seconds. Run "type (Time.time ())" and return the float type. (2The formatted time string (format string): '1999-12-06' Python format symbols in time Date:%Y two-digit year representation (00-99)%Y Four-digit year representation (000-9999)%M month (01-12)%A day in D-month (0-31)%H -Hours of the hour (0-23)%I AHours of the hour (01-12)%M minutes (xx= -)%s seconds (00-59)%A local simplified week name%A Local Full week name%b Local Simplified month name%B Local Full month name%c Local corresponding date representation and time representation%One day in J year (001-366)%P equivalent of local a.m. or p.m.%U number of weeks in the year (00-53) Sunday for the beginning of the week%W Week (0-6), Sunday for the beginning of the week%W the number of weeks in a year (00-53) Monday for the beginning of the week%x Local corresponding date representation%X Local corresponding time representation%Z name of the current time zone%% %Number itself (3) Tuple (struct_time): Struct_time tuples Total9Elements Total nine elements: (year, month, day, time, minute, second, week of the year, Day of the year, etc.) index (index) attribute (Attribute) value (values)0Tm_year (years) such as .1Tm_mon (month)1 -  A2Tm_mday (Sun)1 -  to3Tm_hour (Time)0 -  at4Tm_min (min)0 -  -5Tm_sec (SEC)0 -  -6Tm_wday (Weekday)0 - 6(0Represents Monday)7Tm_yday (day ordinal of the year)1 - 3668TM_ISDST (Daylight saving time) defaults to0# import Time ModuleImportTime# time StampPrint(Time.time ())# 1524576003.2530968#时间字符串Print(Time.strftime ("%y-%m-%d %x"))# 2018-04-24 21:20:03Print(Time.strftime ("%y-%m-%d%h-%m-%s "))# 2018-04-24 21-20-03#时间元组: localtime Converts a timestamp to the struct_time of the current time zonePrint(Time.localtime ())# time.struct_time (tm_year=2018, tm_mon=4, tm_mday=24, tm_hour=21, tm_min=20, tm_sec=3, Tm_wday=1, tm_yday=114, tm_ isdst=0)Summary: Time stamp is the time that the computer can recognize; Time string is the time that a person can understand; tuples are used to manipulate time.

Conversions between several formats

Timestamp--Structured time
Time.gmtime (timestamp) #UTC时间, consistent with local time in London, UK
Time.localtime (timestamp) #当地时间.
For example, we are now implementing this method in Beijing: 8 hour difference from UTC time, UTC time + 8 Hour = GMT

Structured time-time stamping
Time.mktime (structured time)

Structured time--string time
Time.strftime ("format definition", "structured Time") if the structured time parameter does not pass, the current time is real.

String time--structured time
Time.strptime (Time string, string corresponding format)

Structured time--%a%b%d%h:%m:%s%y string
Time.asctime (structured time) if the parameter is not passed, the format string of the current time is returned directly

Timestamp-%a%d%d%h:%m:%s%y string
Time.ctime (timestamp) If the parameter is not passed, the format string of the current time is returned directly

OS Module

An OS module is an interface that interacts with the operating system.

OS.GETCWD () Gets the current working directory, which is the directory path of the current Python script work Os.chdir ("DirName") To change the current script working directory, equivalent to the shell under Cdos.curdir return to the current directory: ('. ') Os.pardir Gets the parent directory string name of the current directory: (' ... ') Os.makedirs (' dirname1/dirname2 ') to generate a multi-level recursive directory Os.removedirs (' dirname1 'If the directory is empty, it is deleted and recursively to the previous level of the directory, if it is also empty, then delete, and so on Os.mkdir (' dirname ') to generate a single-level directory, equivalent to the shell mkdir Dirnameos.rmdir (' dirname 'Delete the single-level empty directory, if the directory is not empty can not be deleted, error, equivalent to the shell rmdir Dirnameos.listdir (' dirname 'Lists all files and subdirectories under the specified directory, including hidden files, and prints a list of os.remove () deletes a file Os.rename ("Oldname","NewName") Rename File/Catalog Os.stat (' Path/filename ') Get File/Directory information OS.SEP output operating system-specific path delimiter, win under"\\", under Linux for"/"OS.LINESEP output The line terminator used by the current platform, win under"\t\n", under Linux for"\ n"OS.PATHSEP output The string used to split the file path win is;, Linux: The Os.name output string indicates the current use of the platform. Win -' NT ';Linux -' POSIX 'Os.system ("Bash Command") Run the shell command to display the Os.popen directly (Bash command). Read () Run the shell commands to get the results of the executionOs.environ getting system environment variablesos.path Os.path.abspath (path) returns path normalized absolute path Os.path.split (path) splits path into directory and file name two tuples return Os.path.dirname (path) Returns the directory of path. is actually the first element of Os.path.split (path). os.path.basename (path) returns the last file name of path. If path ends with a/or \, then a null value is returned. The second element of Os.path.split (path)os.path.exists (path) returns true if path exists, false if path does not existos.path.isabs (path) returns True if path is an absolute pathos.path.isfile (path) returns True if path is a file that exists. Otherwise returns falseos.path.isdir (path) returns True if path is a directory that exists. Otherwise returns falseOs.path.join (path1[, path2[, ...]) When multiple paths are combined, the parameters before the first absolute path are ignoredos.path.getatime (path) returns the last access time of the file or directory to which path is pointingos.path.getmtime (path) returns the last modified time of the file or directory to which path is pointingos.path.getsize (path) returns the size of pathNote: os.stat (' Path/filename ') Gets the structure description of the file/directory informationSTAT Structure:st_mode:inode Protection ModeThe st_ino:inode node number. the device that the St_dev:inode resides on. St_nlink:inode number of links. St_uid: The owner's user ID. St_gid: The group ID of the owner. st_size: The size of the normal file in bytes, including data waiting for certain special files. St_atime: Time of last visit. St_mtime: The time of the last modification. St_ctime: reported by the operating system "CTime". On some systems, such as UNIX, is the time of the most recent metadata change, and on other systems (such as Windows) is the time of creation (see the documentation for the platform for more information). SYS moduleSYS module is an interface that interacts with the Python interpretersys.argv command line argument list, the first element is the path of the program itselfsys.exit (N) exit program, Exit normally on exit (0), error exit Sys.exit (1)Sys.version get version information for Python interpreterSys.path Returns the search path for the module, using the value of the PYTHONPATH environment variable when initializingSys.platform returns the operating system platform namesys.argv, used in the real production environment, such as directly on the Linux system run, you can run the py file while adding parameters to run. such as Redis plus parameter run.  Note: The following two examples need to be emulated in the Linux command line or Windows cmd window: The python py file parameter runs only to see the effect. Example:Import SYSprint (SYS.ARGV) # The first item in a list list is the path where the current file is locatedif sys.argv[1] = = ' Alex ' and sys.argv[2] = = ' 3714 ':print (' login successful ')Else:sys.exit ()user = input (' >>> ')pwd = input (' >>> ')if user = = ' Alex ' and pwd = = ' 3714 ':print (' login successful ')Else:sys.exit ()print (' I can do the functions ')Example 2:debug executes a program that does not display debug information directly, or it can be run with the parameter debug, which displays debug information. Import SYSImport LoggingINP = sys.argv[1] If Len (sys.argv) >1 Else ' WARNING 'Logging.basicconfig (level=getattr (Logging, INP)) # DEBUGnum = int (input (' >>> '))logging.debug (num)a = num *Logging.debug (a)B = a-10Logging.debug (b)C = B + 5print (c)

End
2018-4-24

Iron python27_ Module Learning 2

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.