Python速查表 -- Expression ans Statements

  |  

摘要: Python 速查表,涉及类型、运算符、内置函数、列表函数、字典函数、字符串函数,关键字。笔记是英文的。

【对数据分析、人工智能、金融科技、风控服务感兴趣的同学,欢迎关注我哈,阅读更多原创文章】
我的网站:潮汐朝夕的生活实验室
我的公众号:潮汐朝夕
我的知乎:潮汐朝夕
我的github:FennelDumplings
我的leetcode:FennelDumplings


This is a handy “cheat sheet” that can be useful for refreshing your memory as you start out programming in Python.

$1 Expression

This section summarizes Python expressions.

Table B-1: lists the most important basic (literal) values in Python;
Table B-2: lists the Python operators, along with their precedence (those with high precedence are evaluated before those with low precedence);
Table B-3: describes some of the most important built-in functions;
Tables B-4 ~ B-6: describe the list methods, dictionary methods, and string methods

1-1 basic (literal) values in Python

Type Description Syntax Samples
Integer Numbers without a fractional part 42
Float Numbers with a fractional part 42.5, 42.5e-2
Complex Sum of a real (integer or float) and imaginary number 38 + 4j, 42j
String An immutable sequence of characters ‘foo’, “bar”, “””baz”””, r’\n’

1-2 Python operators along with their precedence

Operator Description Precedence
lambda Lambda expression 1
… if … else Conditional expression 2
or Logical or 3
and Logical and 4
not Logical negation 5
in Membership test 6
not in Negative membership test 6
is Identity test 6
is not Negative identity test 6
< Less than 6
> Greater than 6
<= Less than or equal to 6
>= Greater than or equal to 6
== Equal to 6
!= Not equal to 6
| Bitwise or 7
^ Bitwise exclusive or 8
& Bitwise and 9
<< Left shift 10
>> Right shift 10
+ Addition 11
- Subtraction 11
* Multiplication 12
@ Matrix multiplication 12
/ Division 12
// Integer division 12
% Remainder 12
+ Unary identity 13
- Unary negation 13
~ Bitwise complement 13
** Exponentiation 14
x.attribute Attribute reference 15
x[index] Item access 15
x[index1:index2[:index3]] Slicing 15
f(args…) Function call 15
(…) Parenthesized expression or tuple display 16
[…] List display 16
{key:value, …} Dictionary display 16

1-3 the most important built-in functions

Function Description
abs(number) Returns the absolute value of a number.
all(iterable) Returns True if all the elements of iterable are true; otherwise, it returns False.
any(iterable) Returns True if any of the elements of iterable are true; otherwise, it returns False.
ascii(object) Works like repr, but escapes non-ASCII characters.
bin(integer) Converts an integer to a binary literal, in the form of a string.
bool(x) Interprets x as a Boolean value, returning True or False.
bytearray([string, [encoding[, errors]]]) Creates a byte array, optionally from a given string, with the specified encoding and error handling.
bytes([string, [encoding[, errors]]]) Similar to bytearray, but returns an immutable bytes object.
callable(object) Checks whether an object is callable.
chr(number) Returns a character whose Unicode code point is the given number.
classmethod(func) Creates a class method from an instance method
complex(real[, imag]) Returns a complex number with the given real (and, optionally, imaginary) component.
delattr(object, name) Deletes the given attribute from the given object.
dict([mapping-or-sequence]) Constructs a dictionary, optionally from another mapping or a list of (key, value) pairs. May also be called with keyword arguments.
dir([object]) Lists (most of ) the names in the currently visible scopes, or optionally (most of ) the attributes of the given object.
divmod(a, b) Returns (a // b, a % b) (with some special rules for floats).
enumerate(iterable) Iterates over (index, item) pairs, for all items in iterable. Can supply a keyword argument start, to start somewhere other than zero.
eval(string[, globals[, locals]]) Evaluates a string containing an expression, optionally in a given global and local scope.
filter(function, sequence) Returns a list of the elements from the given sequence for which function returns true.
float(object) Converts a string or number to a float.
format(value[, format_spec]) Returns a formatted version of the given value, in the form of a string. The specification works the same way as the format string method.
frozenset([iterable]) Creates a set that is immutable, which means it can be added to other sets.
getattr(object, name[, default]) Returns the value of the named attribute of the given object, optionally with a given default value.
globals() Returns a dictionary representing the current global scope.
hasattr(object, name) Checks whether the given object has the named attribute.
help([object]) Invokes the built-in help system, or prints a help message about the given object.
hex(number) Converts a number to a hexadecimal string.
id(object) Returns the unique ID for the given object.
input([prompt]) Returns data input by the user as a string, optionally using a given prompt.
int(object[, radix]) Converts a string (optionally with a given radix) or number to an integer.
isinstance(object, classinfo) Checks whether the given object is an instance of the given classinfo value, which may be a class object, a type object, or a tuple of class and type objects.
issubclass(class1, class2) Checks whether class1 is a subclass of class2 (every class is a subclass of itself ).
iter(object[, sentinel]) Returns an iterator object, which is object.iter(), an iterator constructed for iterating a sequence (if object supports getitem), or, if sentinel is supplied, an iterator that keeps calling object in each iteration until sentinel is returned.
len(object) Returns the length (number of items) of the given object.
list([sequence]) Constructs a list, optionally with the same items as the supplied sequence.
locals() Returns a dictionary representing the current local scope (do not modify this dictionary).
map(function, sequence, …) Creates a list consisting of the values returned by the given function when applying it to the items of the supplied sequence(s).
max(object1, [object2, …]) If object1 is a nonempty sequence, the largest element is returned; otherwise, the largest of the supplied arguments (object1, object2, . . .) is returned.
min(object1, [object2, …]) If object1 is a nonempty sequence, the smallest element is returned; otherwise, the smallest of the supplied arguments (object1, object2, . . .) is returned.
next(iterator[, default]) Returns the value of iterator.next(), optionally providing a default if the iterator is exhausted.
object() Returns an instance of object, the base class for all (new-style) classes.
oct(number) Converts an integer number to an octal string.
open(filename[, mode[, bufsize]]) Opens a file and returns a file object. (Has additional optional arguments, e.g., for encoding and error handling.)
ord(char) Returns the Unicode code point of a single character.
pow(x, y[, z]) Returns x to the power of y, optionally modulo z.
print(x, …) Print out a line containing zero or more arguments to standard output, separated by spaces. This behavior may be adjusted with the keyword arguments sep, end, file, and flush.
property([fget[, fset[, fdel[, doc]]]]) Creates a property from a set of accessors.
range([start, ]stop[, step]) Returns a numeric range (a form of sequence) with the given start (inclusive, default 0), stop (exclusive), and step (default 1).
repr(object) Returns a string representation of the object, often usable as an argument to eval.
reversed(sequence) Returns a reverse iterator over the sequence.
round(float[, n]) Rounds off the given float to n digits after the decimal point (default zero). For detailed rounding rules, consult the official documentation.
set([iterable]) Returns a set whose elements are taken from iterable (if given).
setattr(object, name, value) Sets the named attribute of the given object to the given value.
sorted(iterable[, cmp][, key][, reverse]) Returns a new sorted list from the items in iterable. Optional parameters are the same as for the list method sort.
staticmethod(func) Creates a static (class) method from an instance method.
str(object) Returns a nicely formatted string representation of the given object.
sum(seq[, start]) Returns the sum of a sequence of numbers, added to the optional parameter start (default 0).
super([type[, obj/type]]) Returns a proxy that delegates method calls to the superclass.
tuple([sequence]) Constructs a tuple, optionally with the same items as the supplied sequence.
type(object) Returns the type of the given object. type(name, bases, dict) Returns a new type object with the given name, bases, and scope.
vars([object]) Returns a dictionary representing the local scope, or a dictionary corresponding to the attributes of the given object (do not modify the returned dictionary).
zip(sequence1, …) Returns an iterator of tuples, where each tuple contains an item from each of the supplied sequences. The returned list has the same length as the shortest of the supplied sequences.

1-4 list methods

Method Description
aList.append(obj) Equivalent to aList[len(aList):len(aList)] = [obj].
aList.clear() Removes all elements from aList.
aList.count(obj) Returns the number of indices i for which aList[i] == obj.
aList.copy() Returns a copy of aList. Note that this is a shallow copy, so the elements are not copied.
aList.extend(sequence) Equivalent to aList[len(aList):len(aList)] = sequence.
aList.index(obj) Returns the smallest i for which aList[i] == obj (or raises a ValueError if no such i exists).
aList.insert(index, obj) Equivalent to aList[index:index] = [obj] if index >= 0; if index < 0, object is prepended to the list.
aList.pop([index]) Removes and returns the item with the given index (default –1).
aList.remove(obj) Equivalent to del aList[aList.index(obj)].
aList.reverse() Reverses the items of aList in place.
aList.sort([cmp][, key][, reverse]) Sorts the items of aList in place (stable sorting). Can be customized by supplying a comparison function, cmp; a key function, key, which will create the keys for the sorting); and a reverse flag (a Boolean value).

1-5 dictionary methods

Method Description
aDict.clear() Removes all the items of aDict.
aDict.copy() Returns a copy of aDict.
aDict.fromkeys(seq[, val]) Returns a dictionary with keys from seq and values set to val (default None). May be called directly on the dictionary type, dict, as a class method.
aDict.get(key[, default]) Returns aDict[key] if it exists; otherwise, it returns the given default value (default None).
aDict.items() Returns an iterator (actually, a view) of (key, value) pairs representing the items of aDict.
aDict.iterkeys() Returns an iterable object over the keys of aDict.
aDict.keys() Returns an iterator (view) of the keys of aDict.
aDict.pop(key[, d]) Removes and returns the value corresponding to the given key, or the given default, d.
aDict.popitem() Removes an arbitrary item from aDict and returns it as a (key, value) pair.
aDict.setdefault(key[, default]) Returns aDict[key] if it exists; otherwise, it returns the given default value (default None) and binds aDict[key] to it.
aDict.update(other) For each item in other, adds the item to aDict (possibly overwriting existing items). It can also be called with arguments similar to the dictionary constructor, aDict.
aDict.values() Returns an iterator (view) of the values in aDict(possibly containing duplicates).

1-6 string methods

Method Description
string.capitalize() Returns a copy of the string in which the first character is capitalized.
string.casefold() Returns a string that has been normalized in a manner similar to simple lowercasing, more suitable for case-insensitive comparisons between Unicode strings.
string.center(width[, fillchar]) Returns a string of length max(len(string), width) in which a copy of string is centered, padded with fillchar (the default is space characters).
string.count(sub[, start[, end]]) Counts the occurrences of the substring sub, optionally restricting the search to string[start:end].
string.encode([encoding[, errors]]) Returns the encoded version of the string using the given encoding, handling errors as specified by errors (‘strict’, ‘ignore’, or ‘replace’, among other possible values).
string.endswith(suffix[, start[, end]]) Checks whether string ends with suffix, optionally restricting the matching with the given indices start and end.
string.expandtabs([tabsize]) Returns a copy of the string in which tab characters have been expanded using spaces, optionally using the given tabsize (default 8).
string.find(sub[, start[, end]]) Returns the first index where the substring sub is found, or –1 if no such index exists, optionally restricting the search to string[start:end].
string.format(…) Implements the standard Python string formatting. Brace-delimited fields in string are replaced by the corresponding arguments, and the result is returned.
string.format_map(mapping) Similar to using format with keyword arguments, except the arguments are provided as a mapping.
string.index(sub[, start[, end]]) Returns the first index where the substring sub is found, or raises a ValueError if no such index exists, optionally restricting the search to string[start:end].
string.isalnum() Checks whether the string consists of alphanumeric characters.
string.isalpha() Checks whether the string consists of alphabetic characters.
string.isdecimal() Checks whether the string consists of decimal characters.
string.isdigit() Checks whether the string consists of digits.
string.isidentifier() Checks whether the string could be used as a Python identifier.
string.islower() Checks whether all the case-based characters(letters) of the string are lowercase.
string.isnumeric() Checks whether the string consists of numeric characters.
string.isprintable() Checks whether the string consists of printable characters.
string.isspace() Checks whether the string consists of whitespace.
string.istitle() Checks whether all the case-based characters in the string following non-case-based letters are uppercase and all other case-based characters are lowercase.
string.isupper() Checks whether all the case-based characters of the string are uppercase.
string.join(sequence) Returns a string in which the string elements of sequence have been joined by string.
string.ljust(width[, fillchar]) Returns a string of length max(len(string), width) in which a copy of string is left-justified, padded with fillchar (the default is space characters).
string.lower() Returns a copy of the string in which all case-based characters have been lowercased.
string.lstrip([chars]) Returns a copy of the string in which all chars have been stripped from the beginning of the string (the default is all whitespace characters, such as spaces, tabs, and newlines).
str.maketrans(x[, y[, z]]) A static method on str. Constructs a translation table for translate, using a mapping x from characters or ordinals to Unicode ordinals (or None for deletion). Can also be called with two strings representing the from- and to-characters, and possibly a third, with characters to be deleted.
string.partition(sep) Searches for sep in the string and returns (head, sep, tail).
string.replace(old, new[, max]) Returns a copy of the string in which the occurrences of old have been replaced with new, optionally restricting the number of replacements to max.
string.rfind(sub[, start[, end]]) Returns the last index where the substring sub is found, or –1 if no such index exists, optionally restricting the search to string[start:end].
string.rindex(sub[, start[, end]]) Returns the last index where the substring sub is found, or raises a ValueError if no such index exists, optionally restricting the search to string[start:end].
string.rjust(width[, fillchar]) Returns a string of length max(len(string), width) in which a copy of string is right-justified, padded with fillchar (the default is space characters).
string.rpartition(sep) Same as partition, but searches from the right.
string.rstrip([chars]) Returns a copy of the string in which all chars have been stripped from the end of the string (the default is all whitespace characters, such as spaces, tabs, and newlines).
string.rsplit([sep[, maxsplit]]) Same as split, but when using maxsplit, counts from right to left.
string.split([sep[, maxsplit]]) Returns a list of all the words in the string, using sep as the separator (splits on all whitespace if left unspecified), optionally limiting the number of splits to maxsplit.
string.splitlines([keepends]) Returns a list with all the lines in string, optionally including the line breaks (if keepends is supplied and is true).
string.startswith(prefix[, start[, end]]) Checks whether string starts with prefix, optionally restricting the matching with the given indices start and end.
string.strip([chars]) Returns a copy of the string in which all chars have been stripped from the beginning and the end of the string (the default is all whitespace characters, such as spaces, tabs, and newlines).
string.swapcase() Returns a copy of the string in which all the case-based characters have had their case swapped.
string.title() Returns a copy of the string in which all the words are capitalized.
string.translate(table) Returns a copy of the string in which all characters have been translated using table (constructed with maketrans).
string.upper() Returns a copy of the string in which all the case-based characters have been uppercased.
string.zfill(width) Pads string on the left with zeros to fill width (with any initial + or - moved to the beginning).

$2 Statement

a quick summary of each of the statement types in Python.

Simple statements

Simple statements consist of a single (logical) line |

Simple Statement Description
Expression Expressions can be statements on their own. This is especially useful if the expression is a function call or a documentation string.
Assert Assert statements check whether a condition is true and raise an AssertionError (optionally with a supplied error message) if it isn’t.
Assignment Assignment statements bind variables to values. Multiple variables may be assigned to simultaneously(through sequence unpacking), and assignments may be chained.
Augmented Assignment Assignments may be augmented by operators. The operator will then be applied to the existing value of the variable and the new value, and the variable will be rebound to the result. If the original value is mutable, it may be modified instead (with the variable staying bound to the original).
pass The pass statement is a “no-op,” which does nothing. It is useful as a placeholder, or as the only statement in syntactically required blocks where you want no action to be performed.
del The del statement unbinds variables and attributes and removes parts (positions, slices, or slots) from data structures (mappings or sequences). It cannot be used to delete values directly, because values are deleted only through garbage collection.
return The return statement halts the execution of a function and returns a value. If no value is supplied, None is returned.
yield The yield statement temporarily halts the execution of a generator and yields a value. A generator is a form of iterator and can be used in for loops, among other things.
raise The raise statement raises an exception. It may be used without any arguments (inside an except clause, to re-raise the currently caught exception), with a subclass of Exception and an optional argument (in which case, an instance is constructed) or with an instance of a subclass of Exception.
break The break statement ends the immediately enclosing loop statement (for or while) and continues execution immediately after that loop statement.
continue The continue statement is similar to the break statement in that it halts the current iteration of the immediately enclosing loop, but instead of ending the loop completely, it continues execution at the beginning of the next iteration.
import The import statement is used to import names (variables bound to functions, classes, or other values) from an external module. This also covers from future import … statements for features that will become standard in future versions of Python.
global The global statement is used to mark a variable as global. It is used in functions to allow statements in the function body to rebind global variables. Using the global statement is generally considered poor style and should be avoided whenever possible.
nonlocal This is similar to the global statement but refers to an outer scope of an inner function (a closure). That is, if you define a function inside another function and return it, this inner function may refer to—and modify—variables from the outer function, provided they are marked as nonlocal.

Compound Statements

Compound statements contain groups (blocks) of other statements.

Compound Statement Description
if The if statement is used for conditional execution, and it may include elif and else clauses.
while The while statement is used for repeated execution (looping) while a given condition is true. It may include an else clause (which is executed if the loop finishes normally, without any break or return statements, for instance).
for The for statement is used for repeated execution (looping) over the elements of sequences or other iterable objects (objects having an iter method that returns an iterator). It may include an else clause (which is executed if the loop finishes normally, without any break or return statements, for instance).
try The try statement is used to enclose pieces of code where one or more known exceptions may occur and enables your program to trap these exceptions and perform exception-handling code if an exception is trapped. The try statement can combine several except clauses (handling exceptional circumstances) and finally clauses (executed no matter what; useful for cleanup).
with The with statement is used to wrap a block of code using a so-called context manager, allowing the context manager to perform some setup and cleanup actions. For example, files can be used as context managers, and they will close themselves as part of the cleanup.
Function Definitions Function definitions are used to create function objects and to bind global or local variables to these function objects.
Class definitions Class definitions are used to create class objects and to bind global or local variables to these class objects.

Share