Python基础知识速查(上)

Python 基础知识速查


Table of contents

  1. Imports
  2. Data Types
  3. Math
  4. Comparisons and Boolean Operations
  5. Conditional Statements
  6. Lists
  7. Tuples
  8. Strings
  9. Dictionaries
  10. Sets
  11. Defining Functions
  12. Anonymous (Lambda) Functions
  13. For Loops and While Loops
  14. Comprehensions
  15. Map and Filter

1. Imports

In [1]:
# 'generic import' of math module
import math
math.sqrt(25)
Out[1]:
5.0
In [2]:
# import a function
from math import sqrt
sqrt(25)    # no longer have to reference the module
Out[2]:
5.0
In [3]:
# import multiple functions at once
from math import cos, floor
In [4]:
# import all functions in a module (generally discouraged)
from csv import *
In [5]:
# define an alias
import datetime as dt
In [6]:
# show all functions in math module
print(dir(math))
['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']

[Back to top]

2. Data Types

Determine the type of an object:

In [7]:
type(2)
Out[7]:
int
In [8]:
type(2.0)
Out[8]:
float
In [9]:
type('two')
Out[9]:
str
In [10]:
type(True)
Out[10]:
bool
In [11]:
type(None)
Out[11]:
NoneType

Check if an object is of a given type:

In [12]:
isinstance(2.0, int)
Out[12]:
False
In [13]:
isinstance(2.0, (int, float))
Out[13]:
True

Convert an object to a given type:

In [14]:
float(2)
Out[14]:
2.0
In [15]:
int(2.9)
Out[15]:
2
In [16]:
str(2.9)
Out[16]:
'2.9'

Zero, None, and empty containers are converted to False:

In [17]:
bool(0)
Out[17]:
False
In [18]:
bool(None)
Out[18]:
False
In [19]:
bool('')    # empty string
Out[19]:
False
In [20]:
bool([])    # empty list
Out[20]:
False
In [21]:
bool({})    # empty dictionary
Out[21]:
False

Non-empty containers and non-zeros are converted to True:

In [22]:
bool(2)
Out[22]:
True
In [23]:
bool('two')
Out[23]:
True
In [24]:
bool([2])
Out[24]:
True

[Back to top]

3. Math

In [25]:
10 + 4
Out[25]:
14
In [26]:
10 - 4
Out[26]:
6
In [27]:
10 * 4
Out[27]:
40
In [28]:
10 ** 4    # exponent
Out[28]:
10000
In [29]:
5 % 4      # modulo - computes the remainder
Out[29]:
1
In [30]:
# Python 2: returns 2 (because both types are 'int')
# Python 3: returns 2.5
10 / 4
Out[30]:
2
In [31]:
10 / float(4)
Out[31]:
2.5
In [32]:
# force '/' in Python 2 to perform 'true division' (unnecessary in Python 3)
from __future__ import division
In [33]:
10 / 4     # true division
Out[33]:
2.5
In [34]:
10 // 4    # floor division
Out[34]:
2

[Back to top]

4. Comparisons and Boolean Operations

Assignment statement:

In [35]:
x = 5

Comparisons:

In [36]:
x > 3
Out[36]:
True
In [37]:
x >= 3
Out[37]:
True
In [38]:
x != 3
Out[38]:
True
In [39]:
x == 5
Out[39]:
True

Boolean operations:

In [40]:
5 > 3 and 6 > 3
Out[40]:
True
In [41]:
5 > 3 or 5 < 3
Out[41]:
True
In [42]:
not False
Out[42]:
True
In [43]:
False or not False and True     # evaluation order: not, and, or
Out[43]:
True

[Back to top]

5. Conditional Statements

In [44]:
# if statement
if x > 0:
    print('positive')
positive
In [45]:
# if/else statement
if x > 0:
    print('positive')
else:
    print('zero or negative')
positive
In [46]:
# if/elif/else statement
if x > 0:
    print('positive')
elif x == 0:
    print('zero')
else:
    print('negative')
positive
In [47]:
# single-line if statement (sometimes discouraged)
if x > 0: print('positive')
positive
In [48]:
# single-line if/else statement (sometimes discouraged), known as a 'ternary operator'
'positive' if x > 0 else 'zero or negative'
Out[48]:
'positive'

[Back to top]

6. Lists

  • List properties: ordered, iterable, mutable, can contain multiple data types
In [49]:
# create an empty list (two ways)
empty_list = []
empty_list = list()
In [50]:
# create a list
simpsons = ['homer', 'marge', 'bart']

Examine a list:

In [51]:
# print element 0
simpsons[0]
Out[51]:
'homer'
In [52]:
len(simpsons)
Out[52]:
3

Modify a list (does not return the list):

In [53]:
# append element to end
simpsons.append('lisa')
simpsons
Out[53]:
['homer', 'marge', 'bart', 'lisa']
In [54]:
# append multiple elements to end
simpsons.extend(['itchy', 'scratchy'])
simpsons
Out[54]:
['homer', 'marge', 'bart', 'lisa', 'itchy', 'scratchy']
In [55]:
# insert element at index 0 (shifts everything right)
simpsons.insert(0, 'maggie')
simpsons
Out[55]:
['maggie', 'homer', 'marge', 'bart', 'lisa', 'itchy', 'scratchy']
In [56]:
# search for first instance and remove it
simpsons.remove('bart')
simpsons
Out[56]:
['maggie', 'homer', 'marge', 'lisa', 'itchy', 'scratchy']
In [57]:
# remove element 0 and return it
simpsons.pop(0)
Out[57]:
'maggie'
In [58]:
# remove element 0 (does not return it)
del simpsons[0]
simpsons
Out[58]:
['marge', 'lisa', 'itchy', 'scratchy']
In [59]:
# replace element 0
simpsons[0] = 'krusty'
simpsons
Out[59]:
['krusty', 'lisa', 'itchy', 'scratchy']
In [60]:
# concatenate lists (slower than 'extend' method)
neighbors = simpsons + ['ned', 'rod', 'todd']
neighbors
Out[60]:
['krusty', 'lisa', 'itchy', 'scratchy', 'ned', 'rod', 'todd']

Find elements in a list:

In [61]:
# counts the number of instances
simpsons.count('lisa')
Out[61]:
1
In [62]:
# returns index of first instance
simpsons.index('itchy')
Out[62]:
2

List slicing:

In [63]:
weekdays = ['mon', 'tues', 'wed', 'thurs', 'fri']
In [64]:
# element 0
weekdays[0]
Out[64]:
'mon'
In [65]:
# elements 0 (inclusive) to 3 (exclusive)
weekdays[0:3]
Out[65]:
['mon', 'tues', 'wed']
In [66]:
# starting point is implied to be 0
weekdays[:3]
Out[66]:
['mon', 'tues', 'wed']
In [67]:
# elements 3 (inclusive) through the end
weekdays[3:]
Out[67]:
['thurs', 'fri']
In [68]:
# last element
weekdays[-1]
Out[68]:
'fri'
In [69]:
# every 2nd element (step by 2)
weekdays[::2]
Out[69]:
['mon', 'wed', 'fri']
In [70]:
# backwards (step by -1)
weekdays[::-1]
Out[70]:
['fri', 'thurs', 'wed', 'tues', 'mon']
In [71]:
# alternative method for returning the list backwards
list(reversed(weekdays))
Out[71]:
['fri', 'thurs', 'wed', 'tues', 'mon']

Sort a list in place (modifies but does not return the list):

In [72]:
simpsons.sort()
simpsons
Out[72]:
['itchy', 'krusty', 'lisa', 'scratchy']
In [73]:
# sort in reverse
simpsons.sort(reverse=True)
simpsons
Out[73]:
['scratchy', 'lisa', 'krusty', 'itchy']
In [74]:
# sort by a key
simpsons.sort(key=len)
simpsons
Out[74]:
['lisa', 'itchy', 'krusty', 'scratchy']

Return a sorted list (does not modify the original list):

In [75]:
sorted(simpsons)
Out[75]:
['itchy', 'krusty', 'lisa', 'scratchy']
In [76]:
sorted(simpsons, reverse=True)
Out[76]:
['scratchy', 'lisa', 'krusty', 'itchy']
In [77]:
sorted(simpsons, key=len)
Out[77]:
['lisa', 'itchy', 'krusty', 'scratchy']

Insert into an already sorted list, and keep it sorted:

In [78]:
num = [10, 20, 40, 50]
from bisect import insort
insort(num, 30)
num
Out[78]:
[10, 20, 30, 40, 50]

Object references and copies:

In [79]:
# create a second reference to the same list
same_num = num
In [80]:
# modifies both 'num' and 'same_num'
same_num[0] = 0
print(num)
print(same_num)
[0, 20, 30, 40, 50]
[0, 20, 30, 40, 50]
In [81]:
# copy a list (two ways)
new_num = num[:]
new_num = list(num)

Examine objects:

In [82]:
num is same_num    # checks whether they are the same object
Out[82]:
True
In [83]:
num is new_num
Out[83]:
False
In [84]:
num == same_num    # checks whether they have the same contents
Out[84]:
True
In [85]:
num == new_num
Out[85]:
True

[Back to top]

7. Tuples

  • Tuple properties: ordered, iterable, immutable, can contain multiple data types
  • Like lists, but they don't change size
In [86]:
# create a tuple directly
digits = (0, 1, 'two')
In [87]:
# create a tuple from a list
digits = tuple([0, 1, 'two'])
In [88]:
# trailing comma is required to indicate it's a tuple
zero = (0,)

Examine a tuple:

In [89]:
digits[2]
Out[89]:
'two'
In [90]:
len(digits)
Out[90]:
3
In [91]:
# counts the number of instances of that value
digits.count(0)
Out[91]:
1
In [92]:
# returns the index of the first instance of that value
digits.index(1)
Out[92]:
1

Modify a tuple:

In [93]:
# elements of a tuple cannot be modified (this would throw an error)
# digits[2] = 2
In [94]:
# concatenate tuples
digits = digits + (3, 4)
digits
Out[94]:
(0, 1, 'two', 3, 4)

Other tuple operations:

In [95]:
# create a single tuple with elements repeated (also works with lists)
(3, 4) * 2
Out[95]:
(3, 4, 3, 4)
In [96]:
# sort a list of tuples
tens = [(20, 60), (10, 40), (20, 30)]
sorted(tens)    # sorts by first element in tuple, then second element
Out[96]:
[(10, 40), (20, 30), (20, 60)]
In [97]:
# tuple unpacking
bart = ('male', 10, 'simpson')    # create a tuple
(sex, age, surname) = bart        # assign three values at once
print(sex)
print(age)
print(surname)
male
10
simpson

[Back to top]

8. Strings

  • String properties: iterable, immutable
In [98]:
# convert another data type into a string
s = str(42)
s
Out[98]:
'42'
In [99]:
# create a string directly
s = 'I like you'

Examine a string:

In [100]:
s[0]
Out[100]:
'I'
In [101]:
len(s)
Out[101]:
10

String slicing is like list slicing:

In [102]:
s[:6]
Out[102]:
'I like'
In [103]:
s[7:]
Out[103]:
'you'
In [104]:
s[-1]
Out[104]:
'u'

Basic string methods (does not modify the original string):

In [105]:
s.lower()
Out[105]:
'i like you'
In [106]:
s.upper()
Out[106]:
'I LIKE YOU'
In [107]:
s.startswith('I')
Out[107]:
True
In [108]:
s.endswith('you')
Out[108]:
True
In [109]:
# checks whether every character in the string is a digit
s.isdigit()
Out[109]:
False
In [110]:
# returns index of first occurrence, but doesn't support regex
s.find('like')
Out[110]:
2
In [111]:
# returns -1 since not found
s.find('hate')
Out[111]:
-1
In [112]:
# replaces all instances of 'like' with 'love'
s.replace('like', 'love')
Out[112]:
'I love you'

Split a string:

In [113]:
# split a string into a list of substrings separated by a delimiter
s.split(' ')
Out[113]:
['I', 'like', 'you']
In [114]:
# equivalent (since space is the default delimiter)
s.split()
Out[114]:
['I', 'like', 'you']
In [115]:
s2 = 'a, an, the'
s2.split(',')
Out[115]:
['a', ' an', ' the']

Join or concatenate strings:

In [116]:
# join a list of strings into one string using a delimiter
stooges = ['larry', 'curly', 'moe']
' '.join(stooges)
Out[116]:
'larry curly moe'
In [117]:
# concatenate strings
s3 = 'The meaning of life is'
s4 = '42'
s3 + ' ' + s4
Out[117]:
'The meaning of life is 42'

Remove whitespace from the start and end of a string:

In [118]:
s5 = '  ham and cheese  '
s5.strip()
Out[118]:
'ham and cheese'

String substitutions:

In [119]:
# old way
'raining %s and %s' % ('cats', 'dogs')
Out[119]:
'raining cats and dogs'
In [120]:
# new way
'raining {} and {}'.format('cats', 'dogs')
Out[120]:
'raining cats and dogs'
In [121]:
# new way (using named arguments)
'raining {arg1} and {arg2}'.format(arg1='cats', arg2='dogs')
Out[121]:
'raining cats and dogs'

String formatting (more examples):

In [122]:
# use 2 decimal places
'pi is {:.2f}'.format(3.14159)
Out[122]:
'pi is 3.14'

Normal strings versus raw strings:

In [123]:
# normal strings allow for escaped characters
print('first line\nsecond line')
first line
second line
In [124]:
# raw strings treat backslashes as literal characters
print(r'first line\nfirst line')
first line\nfirst line

[Back to top]


你可能感兴趣的:(Python)