[ ]
括起来,[]
是一个空列表,不包含任何值,类似于空字符串,负数下标表示从后边开始,-1
表示列表最后一个下标,它是一种可变的数据类型,值可以添加、删除或改变;+
用于连接两个列表并得到一个新列表;*
用于一个列表和一个整数,实现列表的复制;del
将删除列表中下标处的值;in
、not in
用于确定一个值是否在列表中;cat = ['fat', 'black', 'loud']
size, color, disposition = cat
sort()
方法对列表中排序时需注意的3件事: sort()
方法当场对列表排序;sort()
和sorted()
方法的比较:sort(key = None, reverse = False)
就地改变列表,sorted(iterable, key = None, reverse = False)
返回新的列表,对所有可迭代对象均有效;supplies = ['pens', 'staplers', 'flame-throwers', 'binders']
supplies.sort()
print(supplies)
supplies = ['pens', 'staplers', 'flame-throwers', 'binders']
sortedSupplies = sorted(supplies)
print(supplies)
print(sortedSupplies)
\
:续行字符;( )
,和字符串一样是不可变的,值不能被修改、添加或删除;list()
将元组转换为序列,tuple()
将序列转换为元组;#序列转元组
pets = ['K', 'M', 'N']
print(tuple(pets))
#元组转序列
pets = ('K', 'M', 'N')
print(list(pets))
>>> spam = [0, 1, 2, 4, 5]
>>> chees = spam
>>> cheese[1] = 'Hello'
>>> spam
[0, 'Hello', 2, 4, 5]
>>> cheese
[0, 'Hello', 2, 4, 5]
copy()
和deepcopy()
:处理列表或序列时,若不希望改动影响原来的列表或字典,则使用copy()
函数,若是要复制的列表中包含了列表,则使用deepcopy()
代替;{key:value}
;keys()
、values()
、items()
:分别对应于字典的键、值和键-值对;get(要取得其值的键, 键不存在时返回的备用值)
:>>> picnicItems = {'apples':5, 'cpus':2}
>>> 'I am bringing ' + str(picnicItems.get('cups', 0) + ' cups.'
I am bringing 2 cups.
>>> 'I an bringing ' + str(picnicItems.get('eggs', 0) + ' cups.'
I am bringing 0 eggs.
setdefault(要检查的键, 检查的键不存在时设置的值)
:第一次调用之后即存在,再次调用不会改变第一次赋给的键值;>>> 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'}
pprint()
和pformat()
;
import pprint
info = {'name':'K', 'age': 23}
pprint.pprint(info)
#下列这句和上句结果相同
#print(pprint.pformat(info))
#嵌套的字典和列表
allGuests = {'Alice':{'apple':4, 'pretzels':19},
'Bob':{'apple':3, 'sandwiches':4},
'Carol':{'cups':5, 'apple pies':4}}
def totalBrought(guests, item):
numberBrought = 0;
for k, v in guests.items():
numberBrought += v.get(item, 0)
return numberBrought
print('Apple = ' + str(totalBrought(allGuests, 'apple')))
\
;r
,原始字符串完全忽略所有的转义字符,打印出字符串中所有的倒斜杠;>>> print(r'That is Carol\'s cat.')
That is Carol\'s cat.
>>> print('''Dear Alice,
Eve's cat has been arrested for catnapping, cat burglary, and extortion.
Sincerely,
Bob''')
Dear Alice,
Eve's cat has been arrested for catnapping, cat burglary, and extortion.
Sincerely,
Bob
ljust()
,右对齐rjust()
,居中center()
;pyperclip
模块中的copy()
和paste()
函数;