Python Common function notes

Source: Internet
Author: User
Tags shuffle vars

1.Lambda Lambda is actually a statement, Lambda (x): Body. X is a parameter to a lambda function, which can have any number of arguments (including optional parameters), body is the body of the function, can only be an expression, and returns the value of the expression directly.
>>>f=lambda x:x+1
>>>f (2)
3
>>> (lambda x,y:x+y) (2,3)
5


2.the filter filter (Func, list) accepts two parameters: a function func and a list listing, which returns a list. function Func can have only one parameter. Filter function: All elements in the list are passed as arguments to the function, returning a list of elements that can be returned by another Func
>>>l=[' abc ', ' ACD ', ' 1245 ', ' Ddad ', ' AAA ']
>>> def func (s):
Return S.startswith (' a ')
>>>filter (func, L)
[' abc ', ' ACD ', ' AAA ']

>>> li = [1,2,3,4]

>>> filter (lambda x:x>2, Li)

[3, 4]

2.1 The return of a condition during a cycle

>>> {x for x in ' Abracadabra ' If x isn't in ' abc '}

Set ([' R ', ' d '])

3.the zip Zip function takes as many sequences as parameters, combining all the sequences into one element in the same index as a new sequence of tuples merged into each sequence, with the length of the new sequence whichever is the shortest sequence in the parameter. In addition, the (*) operator can be combined with the zip function to achieve the reverse function of the zip, and the merged sequence will be split into multiple tuple
>>>x=[1,2,3]
>>>y=[' A ', ' B ', ' C ']
>>>zip (x, y)
[(1, ' a '), (2, ' B '), (3, ' C ')]
>>>zip (*zip (x, y))
[(a), (' A ', ' B ', ' C ')]

4.map to manipulate list, return list, bind function to modify each value in list function
>>> list=[1,2,3]
>>> map (Lambda x:x*2,list)
>>> [2, 4, 6]

5.Reduce is a successive operation list of each item, the received parameter is 2, the last returned as a result
>>> def func (x, y):
>>> return X+y
>>> Reduce (func, (+))
>>> 6

6. Sorted dictionary Sort

>>> Import operator
>>> x = {1:2, 3:4, 4:3, 2:1, 0:0}
>>> Sorted (X.iteritems (), Key=operator.itemgetter (1), reverse=true)
[(3, 4), (4, 3), (1, 2), (2, 1), (0, 0)]

>>> Sorted (X.iteritems (), Key=lambda x:x[1], Reverse=false)
[(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]

7. List Dictionary Sort

>>> Li = [{' Name ': ' Wang ', ' Age ': +}, {' name ': ' Zhang ', ' Age ': $}, {' name ': ' Li ', ' Age ': 25}]
>>> Sorted (li, key=lambda x:x[' name '], Reverse=false)
[{' Age ': +, ' name ': ' Li '}, {' Age ': ' + ', ' name ': ' Wang '}, {' Age ': ', ' ' ' ' name ': ' Zhang '}]

>>> Sorted (Li, Key=operator.itemgetter (' name '), reverse=true)
[{' Age ': ' "' Name ': ' Zhang '}, {' Age ': +, ' name ': ' Wang '}, {' Age ': +, ' name ': ' Li '}]

8. Flipping a string

>>> s = "ABCD"

>>> S[::-1]

' DCBA '

>>> "". Join (sorted (list (s), reverse=true))

' DCBA '

9. Conversion between Ganso (tuple), dictionary (dict)

>>> t = ((1, "a"), (2, "B"))

>>> dict (t) #元祖转字典

{1: ' A ', 2: ' B '}

>>> d = dict (t)

>>> D.items () #字典转元祖

[(1, ' a '), (2, ' B ')]

>>> T = (1, "a")

>>> dict ([t]) #单个元祖转字典

{1: ' A '}

>>> d = dict ([t])

>>> D.popitem ()

(1, ' a ')

>>> d.items () [0] #单个字典转元祖

(1, ' a ')

Increase key Value name

>>> Li = [{1: "A"},{2: "B"}]

>>> [Dict (("Key", "value"), Obj.items () [0]))) for obj in Li]

[{' Value ': ' A ', ' key ': 1}, {' Value ': ' B ', ' Key ': 2}]

>>> Map (Lambda x:dict ("key", "value"), X.items () [0]), Li)

[{' Value ': ' A ', ' key ': 1}, {' Value ': ' B ', ' Key ': 2}]

>>> Li2 = [{' Value ': ' A ', ' key ': 1}, {' Value ': ' B ', ' Key ': 2}]

>>> [{obj["key"]:obj["value"]} for obj in Li2]

[{1: ' a '}, {2: ' B '}]

Grouping object values within a list

>>> Li = [{"K": "1", "V": "V1"},{"K": "2", "V": "V2"},{"K": "1", "V": "V3"}]

>>> keys = set (Map (lambda x:x["K"], Li)) # Remove the key value

>>> NewList = [{"K": X, "V": [y["V"] for y in Li if y["K"]==x]} for x in keys]

>>> Print NewList

[{' K ': ' 1 ', ' V ': [' v1 ', ' v3 ']}, {' K ': ' 2 ', ' V ': [' V2 ']}]

Printing All the properties and values of an object

For property, value in VARs (theobject). Iteritems ():

Print property, ":", Value

This is actually theobject.__dict__, that is, VARs (obj) is actually returning o.__dict__

one by one. List pagination

>>> mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> Print [mylist[i:i+4] for I in range (0, Len (mylist), 4)]

[[1, 2, 3, 4], [5, 6, 7, 8], [9]]

List Step

Syntax: L[start:stop:step]

MyList = [1,2,3,4,5,6,7,8,9,10]

For I in Mylist[::2]:

Print I,

# prints 1 3 5 7 9

For I in Mylist[1::2]:

Print I,

# prints 2 4 6 8 10

>>> Range (1, 10, 2)

[1, 3, 5, 7, 9]

python string formatting, 2.7 after adding a new string formatting method format, preceded by the% symbol

>>> ' {},{} '. Format (' AA ', ' BB ')

' Aa,bb '

>>> "{0},{2},{1}". Format (+/-)

' 1,3,2 '

>>> "{0},{2},{1},{str}". Format (1,2,3,str= "string")

' 1,3,2,string '

>>> ' {0[0]},{0[1]} '. Format ([' AA ', "BB"])

' Aa,bb '

>>> ' {: >10} '. Format (' 12 ') # String left space padding

' 12 '

>>> ' {: a<10} '. Format (' 12 ') # String to the right of the letter "a" padding

' 12aaaaaaaa '

>>> ' {:. 2f} '. Format (321.33345) # floating-point type

' 321.33 '

>>> ' {: b} '. Format (17) # formatted as a binary

' 10001 '

>>> ' {: x} '. Format (17) # Hex

' 11 '

>>> "&nbsp;" * 4 # Copy multiple strings

' &nbsp;&nbsp;&nbsp;&nbsp; '

Random Number

Randomly pick a string:

>>> Import Random

>>> random.choice ([' Apple ', ' pear ', ' peach ', ' orange ', ' Lemon '])

' Lemon '

Shuffle:

>>> items = [1, 2, 3, 4, 5, 6]

>>> random.shuffle (items)

>>> Items

[3, 2, 5, 6, 4, 1]

Select a specific number of characters in more than one character:

>>> random.sample (' Abcdefghij ', 3)

[' A ', ' d ', ' B ']

Random integers:

>>> Random.randint (0,99)

21st

Randomly select even numbers between 0 and 100:

>>> random.randrange (0, 101, 2)

42

Dynamic Object operations

14.1 Dynamic Execution Expressions

>>> x = 1
>>> Print eval (' x+1 ') # This function evaluates the string str as a valid Python expression and returns the result of the calculation, but does not dynamically update the value, such as eval ("x=2"), which results in an error.
2

14.2 dynamically get updated variable values

>>> d = {"name": "Wei"}
>>> D2 = {"Age": 20}
>>> VARs () [' d ']
{' name ': ' Wei '}
>>> VARs () [' d '].update (D2) # If the global variable uses globals ()
>>> Print D
{' Age ': ' ' name ': ' Wei '}
>>> D3 = {"Phone": "139"}
>>> exec ("D.update (D3)")
>>> Print D
{' Phone ': ' 139 ', ' age ': ' name ': ' Wei '}
>>> print VARs () ["D"]
{' Phone ': ' 139 ', ' age ': ' name ': ' Wei '}
The >>> print exec ("D") # EXEC statement executes the string str as valid Python code, but does not return a value.
File "<input>", line 1
Print exec ("D")
^
Syntaxerror:invalid syntax

14.3 Dynamic Get Set property value

U = User.objects.get (id=1)
name = GetAttr (U, "username", "Wei") # The third parameter does not have a default value
Kwargs = {"username": name}
User.objects.filter (id=1). Update (**kwargs)
SetAttr (U, "username", "Wei")

Python Common function notes

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: [email protected] 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.