Python Tips

1 builtin functions

1.1 range的三种形式

range(5)          # 0 1 2 3 4
range(1, 6)       # 1 2 3 4 5
range(5, 0, -1)   # 5 4 3 2 1

2 作用域

There are four rules to tell whether a variable is in a local scope or global scope:

  • If a variable is being used in the global scope (that is, outside of all functions), then it is always a global variable.
  • If there is a global statement for that variable in a function, it is a global variable.
  • Otherwise, if the variable is used in an assignment statement in the function, it is a local variable.
  • But if the variable is not used in an assignment statement, it is a global variable.

2.1 变量作用域要么全局,要么局部

In a function, a variable will either always be global or always be local. There’s no way that the code in a function can use a local variable named eggs and then later in that same function use the global eggs variable.

def spam():
	print(eggs) # ERROR!
	eggs = 'spam local'

eggs = 'global'
spam()

以上程序执行报错:UnboundLocalError: local variable 'eggs' referenced before assignment

Python sees that there is an assignment statement for eggs in the spam() function and therefore considers eggs to be local. But because print(eggs) is executed before eggs is assigned anything, the local variable eggs doesn’t exist. Python will not fall back to using the global eggs variable.

3 List

3.1 List内可存储不同的数据类型的数据,甚至是其它List

['hello', 3.1415, True, None, 42, [11, 22]]

3.2 负数索引

spam = ['hello', 3.1415, True, None, 42]
  • spam[-1]: 42
  • spam[-2]: None
  • spam[-3]: True
  • spam[-4]: 3.1415
  • spam[-5]: ‘hello’
  • spam[-6]: IndexError

3.3 切片操作是深拷贝

>>> a = [1,2,3,4,5]
>>> b = a[2:4]
>>> b[1] = 44
>>> b
[3, 44]
>>> a
[1, 2, 3, 4, 5]

3.4 但赋值是浅拷贝(引用)

>>> l = [1,2,3,4,5]
>>> c = l
>>> c[0] = 11
>>> c
[11, 2, 3, 4, 5]
>>> l
[11, 2, 3, 4, 5]

3.5 删除元素

3.5.1 del语句

>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> del spam[2]
>>> spam
['cat', 'bat', 'elephant']
>>> del spam[2]
>>> spam
['cat', 'bat']

3.5.2 remove方法

>>> l = [1,2,3,4]
>>> l.remove(2)
>>> l
[1, 3, 4]

注意,remove方法的参数是元素的值

3.5.3 pop方法删除最后一个元素

>>> l
[1, 3, 4]
>>> l.pop()
4
>>> l
[1, 3]

append和pop结合可以实现栈

3.6 传递列表到函数内,可以给列表添加或删除元素(与go不同)

def eggs(someParameter):
    someParameter.append('Hello')

spam = [1, 2, 3]
eggs(spam)
print(spam) # [1, 2, 3, 'Hello']

3.7 copy and deepcopy

The first of these, copy.copy(), can be used to make a duplicate copy of a mutable value like a list or dictionary, not just a copy of a reference.

>>> import copy
>>> spam = ['A', 'B', 'C', 'D']
>>> cheese = copy.copy(spam)
>>> cheese[1] = 42
>>> spam
['A', 'B', 'C', 'D']
>>> cheese
['A', 42, 'C', 'D']

If the list you need to copy contains lists, then use the copy.deepcopy() function instead of copy.copy(). The deepcopy() function will copy these inner lists as well.

>>> list1 = [1, 2, 3, [4, 5, 6]]
>>> list2 = copy.copy(list1)
>>> list3 = copy.deepcopy(list1)
>>> list1
[1, 2, 3, [4, 5, 6]]
>>> list2
[1, 2, 3, [4, 5, 6]]
>>> list3
[1, 2, 3, [4, 5, 6]]
>>> list1[3].append(7)
>>> list1
[1, 2, 3, [4, 5, 6, 7]]
>>> list2
[1, 2, 3, [4, 5, 6, 7]]
>>> list3
[1, 2, 3, [4, 5, 6]]
>>> id(list1[3])
1862769970632
>>> id(list2[3])
1862769970632
>>> id(list3[3])
1862769943368
>>> 

参考: copy in Python (Deep Copy and Shallow Copy)

4 变量交换

>>> a, b = 'Alice', 'Bob'
>>> a, b = b, a
>>> print(a)
'Bob'
>>> print(b)
'Alice'

5 字符串

5.1 字符串是只读类型

>>> name = 'Zophie a cat'
>>> name[7] = 'the'
Traceback (most recent call last):
  File "<pyshell#50>", line 1, in <module>
    name[7] = 'the'
TypeError: 'str' object does not support item assignment

5.2 可以使用list函数转换字符串为单字符的列表

>>> s = "hello"
>>> l = list(s)
>>> l
['h', 'e', 'l', 'l', 'o']
>>> s
'hello'

5.3 raw string

A raw string completely ignores all escape characters and prints any backslash that appears in the string.

>>> print(r'That is Carol\'s cat.')
That is Carol\'s cat.

5.4 string interpolation and f-string

string interpolation:

>>> name = 'Al'
>>> age = 4000
>>> 'My name is %s. I am %s years old.' % (name, age)
'My name is Al. I am 4000 years old.'

f-string:

>>> name = 'Al'
>>> age = 4000
>>> f'My name is {name}. Next year I will be {age + 1}.'
'My name is Al. Next year I will be 4001.'

Remember to include the f prefix; otherwise, the braces and their contents will be a part of the string value:

>>> 'My name is {name}. Next year I will be {age + 1}.'
'My name is {name}. Next year I will be {age + 1}.'

5.5 isupper和islower要求字符串至少包含一个字符

The isupper() and islower() methods will return a Boolean True value if the string has at least one letter and all the letters are uppercase or lowercase, respectively.

>>> spam = 'Hello, world!'
>>> spam.islower()
False
>>> spam.isupper()
False
>>> 'HELLO'.isupper()
True
>>> 'abc12345'.islower()
True
>>> '12345'.islower()
False
>>> '12345'.isupper()
False

5.6 isX方法

  • isalpha() Returns True if the string consists only of letters and isn’t blank
  • isalnum() Returns True if the string consists only of letters and numbers and is not blank
  • isdecimal() Returns True if the string consists only of numeric characters and is not blank
  • isspace() Returns True if the string consists only of spaces, tabs, and newlines and is not blank
  • istitle() Returns True if the string consists only of words that begin with an uppercase letter followed by only lowercase letters
>>> 'hello'.isalpha()
True
>>> 'hello123'.isalpha()
False
>>> 'hello123'.isalnum()
True
>>> 'hello'.isalnum()
True
>>> '123'.isdecimal()
True
>>> '    '.isspace()
True
>>> 'This Is Title Case'.istitle()
True
>>> 'This Is Title Case 123'.istitle()
True
>>> 'This Is not Title Case'.istitle()
False
>>> 'This Is NOT Title Case Either'.istitle()
False

5.7 split指定参数位于字符串头/尾时,结果会多一个空字符串

>>> s = "abcdabcdabcd"
>>> s.split('a')
['', 'bcd', 'bcd', 'bcd']
>>> s.split('d')
['abc', 'abc', 'abc', '']

5.8 按照指定字符分割三段

>>> 'Hello, world!'.partition('w')
('Hello, ', 'w', 'orld!')

>>> 'Hello, world!'.partition('o')
('Hell', 'o', ', world!')

>>> 'Hello, world!'.partition('XYZ')
('Hello, world!', '', '')

注意返回类型是tuple

5.9 补充字符以对齐字符串

def printPicnicTable(table, leftWidth, rightWidth):
    print("Picnic Table".center(leftWidth + rightWidth, '-'))
    for item, count in table.items():
        print(item.ljust(leftWidth, '.') + str(count).rjust(rightWidth))

if __name__ == "__main__":
    picnicTable = {"sandwiches": 4, "apples": 12, "cups": 4, "cookies": 800}
    printPicnicTable(picnicTable, 20, 5)
    printPicnicTable(picnicTable, 25, 10)

执行结果如下:

-------Picnic Table------
sandwiches..........    4
apples..............   12
cups................    4
cookies.............  800
------------Picnic Table-----------
sandwiches...............         4
apples...................        12
cups.....................         4
cookies..................       800

5.10 带参数的strip

>>> spam = 'SpamSpamBaconSpamEggsSpamSpam'
>>> spam.strip('ampS')
'BaconSpamEggs'

Passing strip() the argument ‘ampS’ will tell it to strip occurrences of a, m, p, and capital S from the ends of the string stored in spam. The order of the characters in the string passed to strip() does not matter: strip(‘ampS’) will do the same thing as strip(‘mapS’) or strip(‘Spam’).

5.11 ASCII码与字符的转换

>>> ord('A')
65
>>> ord('4')
52
>>> ord('!')
33
>>> chr(65)
'A'

5.12 剪贴板copy/paste

>>> import pyperclip
>>> pyperclip.copy('Hello, world!')
>>> pyperclip.paste()
'Hello, world!'

Of course, if something outside of your program changes the clipboard contents, the paste() function will return it. For example, if I copied this sentence to the clipboard and then called paste(), it would look like this:

>>> pyperclip.paste()
'For example, if I copied this sentence to the clipboard and then called
paste(), it would look like this:'

6 元组Tuple

6.1 元组是只读类型

>>> eggs = ('hello', 42, 0.5)
>>> eggs[1] = 99
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    eggs[1] = 99
TypeError: 'tuple' object does not support item assignment

6.2 单元素的元组定义必须加显式的逗号,否则会被视为一个加了括号的变量

>>> t = (1,)
>>> type(t)
<class 'tuple'>
>>> v = (1)
>>> type(v)
<class 'int'>

6.3 什么时候使用Tuple替代List

If you need an ordered sequence of values that never changes, use a tuple. A second benefit of using tuples instead of lists is that, because they are immutable and their contents don’t change, Python can implement some optimizations that make code using tuples slightly faster than code using lists.

7 字典

7.1 keys()、values()、items()分别用于获取所有的键、值、键值对

>>> spam = {'color': 'red', 'age': 42}
>>> for v in spam.values():
        print(v)

red
42

>>> for k in spam.keys():
        print(k)

color
age
>>> for i in spam.items():
        print(i)

('color', 'red')
('age', 42)

7.2 in、not in可用于判断键/值是否存在

>>> spam = {'name': 'Zophie', 'age': 7}
>>> 'name' in spam.keys()
True
>>> 'Zophie' in spam.values()
True
>>> 'color' in spam.keys()
False
>>> 'color' not in spam.keys()
True
>>> 'color' in spam
False

Notice that ‘color’ in spam is essentially a shorter version of writing ‘color’ in spam.keys().If you ever want to check whether a value is (or isn’t) a key in the dictionary, you can simply use the in (or not in) keyword with the dictionary value itself.

7.3 get方法

>>> picnicItems = {'apples': 5, 'cups': 2}
>>> 'I am bringing ' + str(picnicItems.get('cups', 0)) + ' cups.'
'I am bringing 2 cups.'
>>> 'I am bringing ' + str(picnicItems.get('eggs', 0)) + ' eggs.'
'I am bringing 0 eggs.'

a get() method that takes two arguments: the key of the value to retrieve and a fallback value to return if that key does not exist.

7.4 setdefault方法

message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {}

for character in message:
    count.setdefault(character, 0)
    count[character] = count[character] + 1

print(count)

The first argument passed to the method is the key to check for, and the second argument is the value to set at that key if the key does not exist. If the key does exist, the setdefault() method returns the key’s value.

>>> spam = {'name': 'Pooka', 'age': 5}
>>> spam.setdefault('color', 'black')
'black'
>>> spam
{'color': 'black', 'age': 5, 'name': 'Pooka'}
>>> spam.setdefault('color', 'white')
'black'
>>> spam
{'color': 'black', 'age': 5, 'name': 'Pooka'}

8 注释

8.1 三括号字符串可以用于多行注释

"""This is a test Python program.
Written by Al Sweigart al@inventwithpython.com

This program was designed for Python 3, not Python 2.
"""

def spam():
    """This is a multiline comment to help
    explain what the spam() function does."""
    print('Hello!')


spam()

该程序打印:Hello!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值