Python Shell: Code structure

Source: Internet
Author: User

Using a zip () parallel iteration

days = [' Monday ', ' Tuesday ', ' Wednesday ']
>>> fruits = [' banana ', ' orange ', ' peach ']
>>> drinks = [' coffee ', ' tea ', ' beer ']
>>> desserts = [' tiramisu ', ' ice cream ', ' pie ', ' pudding ']
>>> for day, fruit, drink, dessert in zip (days, fruits, drinks, desserts):
... print (Day, ": Drink", drink, "-eat", fruit, "-enjoy", dessert)
...
Monday:drink coffee-eat Banana-enjoy Tiramisu
Tuesday:drink Tea-eat Orange-enjoy Ice cream
Wednesday:drink beer-eat Peach-enjoy Pie

中文版 = ' Monday ', ' Tuesday ', ' Wednesday '
>>> French = ' Lundi ', ' Mardi ', ' mercredi '

Now use the zip () function to pair two tuples. The return value of a function is neither a tuple nor a list, but a consolidated
Python Shell: Code structure | 71
An iterative variable that is together:

List (English, French)
[(' Monday ', ' Lundi '), (' Tuesday ', ' Mardi '), (' Wednesday ', ' mercredi ')]

A miniature English-French dictionary can be obtained with the return value of the Dict () function and the zip () function:
>>> dict (Zip (中文版, French))
{' Monday ': ' Lundi ', ' Tuesday ': ' Mardi ', ' Wednesday ': ' mercredi '}

[ expression for item ' in iterable ]

The following example creates a list of integers from a list derivation:

>>> number_list = [number for number in range (1,6)]
>>> number_list
[1, 2, 3, 4, 5]

rows = Range (1,4)
>>> cols = range (1,3)
>>> cells = [(row, col) for row in rows for col in cols]
>>> for cell in cells:
.. print (cell)

A_list = [number for number in range (1,6) if number% 2 = = 1]

Dictionary derivation formula:

>>> word = ' letters '
>>> letter_counts = {Letter:word.count (letter) for letter in Set (word)}
>>> letter_counts
{' t ': 2, ' l ': 1, ' E ': 2, ' R ': 1, ' s ': 1}

Set Derivation:

A_set = {number for number in range (1,6) if number% 3 = = 1}
>>> A_set
{1, 4}

Generator derivation:

A generator can run only once. Lists, collections, strings, and dictionaries are stored in memory, but
Is that the generator only generates values in the run and is not stored, so it cannot be reused or backed up
A generator.

Between the parentheses is the generator derivation

Number_thing = (number for number in range (1, 6))

For number in number_thing:
... print (number)

Integer/float of value 0, empty string ('), empty list ([]),
The Empty tuple ((,)), Empty dictionary ({}), empty collection (set ()) are all equivalent to False, but not equal to none

def is_none (thing):
... if thing is None:
... print ("It ' s None")
... elif thing:
... print ("It ' s True")
.. else:
... print ("It ' s False")

The default parameter value is calculated when the function is defined, not when the program is running. Python Process
A common mistake the sequencer makes is to treat a variable data type (such as a list or dictionary) as the default
The parameter value.

def buggy (ARG, result=[]):
... result.append (ARG)
.. print (Result)
...
>>> Buggy (' a ')
[' A ']
>>> Buggy (' B ') # expect [' B ']
[' A ', ' B ']

def works (ARG):
... result = []
... result.append (ARG)
... return result
...
>>> works (' a ')
[' A ']
>>> works (' B ')
[' B ']

def nonbuggy (ARG, Result=none):
... if result is None:
... result = []
... result.append (ARG)
.. print (Result)
...
>>> nonbuggy (' a ')
[' A ']
>>> nonbuggy (' B ')
[' B ']

Use * to collect location parameters:

When an argument is used inside a function, the asterisk synthesizes a set of variable number of positional parameter sets to the tuple of the parameter values

All parameters passed in to the function return the output as tuples:

def Print_args (*args):
... print (' positional argument tuple: ', args)

Print_args (3, 2, 1, ' wait! ', ' uh ... ')
Positional argument tuple: (3, 2, 1, ' wait! ', ' uh ... ')

def print_more (required1, Required2, *args):
... print (' Need this one: ', required1)
... print (' Need this one too: ', required2)
... print (' All the rest: ', args)
...
>>> print_more (' cap ', ' gloves ', ' scarf ', ' monocle ', ' mustache wax ')
Need this One:cap
Need this one too:gloves
All the rest: (' scarf ', ' monocle ', ' mustache wax ')

Use * * to collect keyword parameters:

Use two asterisks to collect parameters into a dictionary, the name of the parameter is the key of the dictionary, the value of the corresponding parameter is the word
The value of the code

def Print_kwargs (**kwargs):
... print (' Keyword arguments: ', Kwargs)

Print_kwargs (wine= ' Merlot ', entree= ' mutton ', dessert= ' macaroon ')
Keyword arguments: {' dessert ': ' macaroon ', ' wine ': ' Merlot ', ' entree ': ' Mutton '}

Closures:

An intrinsic function can be thought of as a closure. A closure is a function that can be dynamically generated by another function and can be changed
Variables that are created outside of the variable and stored function values

def knights2 (saying):
... def inner2 ():
... return "We are the Knights say: '%s '"% saying
... return Inner2

capitalize the first letter of each word: word.capitalize ()

Python provides two functions to get the contents of a namespace:


? Locals () returns a dictionary of the contents of a local namespace;
? Globals () returns a dictionary of the contents of a global namespace.

Python Shell: Code structure

Related Article

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.