Wang 's Python Learning Path (vii)-date,continue, iteration object, generator

Source: Internet
Author: User
Tags dateformat iterable local time


Reprint please indicate the source: Wang  's way of Daniel


Most languages provide the appropriate classes of time operations, such as Java java.util.Date,Java.util.Calendar , and so on,
In Python, It is time and calendar .



First you need a guide packageimport time;



And then you can use it, and whatmTime= time.time()happens?


1448004021.1337154 (and this number continues to change)


Why?


Returns the current operating system time from 12:00AM, January 1, 1970 (epoch) with ticks chronograph units, GMT you know.


There are similar implementations in Java, like the following:


Date date = new Date ();
System.out.println (date.getTime ());

Results: 1448004275140 


How does it show our usual time of the second Ah, the day or the like?



The implementation in Java is:


Date date = new Date ();
  DateFormat df1 = DateFormat.getDateInstance (DateFormat.FULL, Locale.CHINA);
  System.out.println (df1.format (date));

Results: Friday, November 20, 2015


And in Python:


localtime = time.localtime (time.time ())
print ("Line 107, local time:", localtime)
#Time format
print ("Line 109, printing the formatted local time", time.asctime (localtime))

Result: Line 107, local time: time.struct_time (tm_year = 2015, tm_mon = 11, tm_mday = 20, tm_hour = 15, tm_min = 20, tm_sec = 21, tm_wday = 4, tm_yday = 324, tm_isdst = 0)
         Line 109, print the formatted local time Fri Nov 20 15:20:21 2015 


Fri 15:20:21 is it look familiar? , what is the long string of 107 lines of print?


The Python function uses a single element to assemble 9 sets of digital processing time, each of which represents the following meaning:
year, month, day, hour, minute, second day of the week, the first day of the year, whether daylight saving time

,time.asctime()the method is then called to format the element in a format that we understand more effectively.


The calendar is also associated with the event, and Python has a very good layer of packaging for calendars, such as I want to play all the calendars for a certain January of a year, just one line of codecalendar.month(2015,11)



Results:


November 2015
Mo Tu We Th Fr Sa Su
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30


Is it instantaneous energy?
There are also the total number of leap years, such as returning between two.


print (calendar.leapdays (2000,2009), "year")

Results: 3 years 


Python Continue statement


The continue statement jumps out of the loop, and break jumps out of the loop meaning and almost all of Java is a direct terminal this step back to the starting point of the loop, see example:

for x in "HelloWorldhaha":
         if x == "r":
             continue
         print ("now word:", x, end = "")
         if x == "a":
             break

Result: now word: H now word: e now word: l now word: l now word: o now word: W now word: o now word: l now word: d now word: h now word: a NiHao current number 0

The first logic just makes the r set of prints not executed, and the second set of logic breaks to end the entire loop, so the difference between the two is still big, and neither is a single round of one thing.


Another post ** pass ** example
for x in range (10):
     if x% 3 == 0:
         pass
         print ("NiHao", end = "")
     print ("current number", x)

Results:
Current number 1
Current number 2
NiHao current number 3
Current number 4
Current number 5
NiHao current number 6
Current number 7
Current number 8
NiHao current number 9

So, pass means nothing happened. . 


Python Builder


In Python, this side loop computes the mechanism, called the generator: Generator. A generator is created as soon as a list-generated [] is changed to ().

print ("print list on line 8", [x for x in range (10)])

Result: line 8 prints list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

// create a generator
print ("Print generator for line 11", (x for x in range (10)))

Result: line 39 prints the deformed fib <generator object fib at 0x000000F008E43AF0> 


Generator cannot be printed directly, and we can use the next () function to read it one by one (and not to get his length).



In the same way, we can use a for loop and other iterative methods to read the contents of his


g = (x for x in range (10))
#Iterable
for x in g:
     print (x, end = "")
Results: 0 1 2 3 4 5 6 7 8 9

Or use
  next (g)
Results: 0 


So if you can't read something with Next (), you'll throw an exception, like this.



Traceback (most recent):
File "", Line 1, in
Stopiteration



Generator also provides a keyword yieldthat looks like the function and return, but the run-to-yield function stops and records the position where the next call will begin.


def testYie ():
     print ("First execution here")
     yield 1
     print (‘second execution here’)
     yield 3
     print (‘the third execution here’)
     yield 5
#Need to construct a function object first
newTestYie = testYie ()

print (next (newTestYie))
print (next (newTestYie))
print (next (newTestYie))
Yield must be in a function and must not appear in the base class.

Results:
First execution here
1
The second execution here
3
The third execution here
5

From the normal understanding of the results, it seems that the function is called only once, but it is not, it is executed only three times, and this result appears.

If you call it again, the exception just appeared 


This function is the generator function when a function appears in the yield keyword.



Iterate objects



The concept of iteration and how it has been mentioned before, and what is to be emphasized today are iterable objects and Iterator objects



From the Internet


A class is a collection of data types, such as list, tuple, dict, set, str, and so on;

A class is generator, including generators and generator function with yield.

These objects that can directly act on a for loop are called an iterative object: Iterable.

An object that can be called by the next () function and continually returns the next value is called an iterator: Iterator.


We can use the Isinstance function to determine the type of object, such as:


#Determine if it is an iterable object
print (‘Line 77 determines whether the string is an iterable object’, isinstance ("as", Iterable))
print (‘Line 78 determines whether the list is an iterable object’, isinstance ([], Iterable))
print (‘Line 79 determines whether the dictionary is an iterable object’, isinstance ({"aa": 123, "cc": 123}, Iterable))

# Determine whether to iterate over the object Iterator
print (‘Line 82 determines whether the dictionary is an iteration object’, isinstance ({"aa": 123, "cc": 123}, Iterator))
print (‘Line 83 determines whether the list is an iteration object’, isinstance ([x for x in range (10)], Iterator))
print ('Line 84 determines whether the generator is an iteration object', isinstance ((x for x in range (10)), Iterator))

Results:
Line 77 determines whether the string is an iterable object True
Line 78 determines if list is an iterable object True
Line 79 determines if the dictionary is an iterable object True

Line 82 determines whether the dictionary is an iteration object False
Line 83 determines whether the list is an iteration object False
Line 84 determines whether the generator is an iteration object True 


The two types can also be converted to each other:


#Convert to Iterator Object
print (‘Line 87 Iterable is converted to an Iterator object’, isinstance (iter ([x for x in range (10)]), Iterator))

Line 87 Iterable converted to Iterator object True 


So, why do you need iterator with iterable? (Good to the mouth, very difficult to remember)


This is because the Python iterator object represents a data stream, and the iterator object can be called by the next () function and continuously return to the next data until the Stopiteration error is thrown when there is no data. This data stream can be viewed as an ordered sequence, but we cannot know the length of the sequence in advance, but we will only continue to calculate the next data on demand through the next () function, so the calculation of iterator is inert and is only calculated when the next data needs to be returned.
Iterator can even represent an infinitely large stream of data, such as the whole natural number. Using list is never possible to store all natural numbers.


The example also has a 99 multiplication table and a Pascal series, more examples can be directly read the source code:
https://github.com/ddwhan0123/PythonExample/blob/master/%E7%A4%BA%E4%BE%8B/l5demo.py



Thanks






Wang 亟亟 's Python Learning Path (vii)-date,continue, iteration object, generator


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.