Python基础教程(第3版) 笔记(四)

第二章 列表和元素
2.1 序列概述
列表和元组的主要不同在于,列表是可以修改的,而元组不可以。
创建一个由数据库中所有人员组成的列表:
>>> edward = ['Edward Gumby', 42]
>>> john = ['John Smith', 50]
>>> database = [edward, john]
>>> database
[['Edward Gumby', 42], ['John Smith', 50]]
2.2.1索引
序列中的所有元素都有编号——从0开始递增。
>>> greeting = 'Hello'
>>> greeting[0]
'H'
当使用负索引时,从最后一个数字开始,-1为最后一个元素的位置
>>> greeting[-1]
'o'

>>> 'Hello'[1]
'e'
获取用户输入的年份的第四位:
>>>fourth=input('Year: ')[3]
Year: 2005
>>> fourth
'5'
2.2.2 切片
使用切片来访问范围内的元素
>>> tag = '<a href="http://www.python.org">Python web site</a>'
>>> tag[9:30]
'http://www.python.org'
>>> tag[32:-4]
'Python web site'
其中第一个索引是第一个元素的编号(编号从0开始),第二个索引是切片后余下的第一个元素的编号(也就是看成再减一位就行[向开始的位置减])
>>> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> numbers[3:6] [4, 5, 6]
>>> numbers[0:1] [1]
1. 绝妙的简写
>>> numbers[-3:-1] 负索引
[8, 9]
如果切片结束于序列末尾,可省略第二个索引。
>>> numbers[-3:]
[8, 9, 10]
同样,如果切片始于序列开头,可省略第一个索引。
>>> numbers[:3]
[1, 2, 3]
要复制整个序列,可将两个索引都省略。
>>> numbers[:]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
2. 更大的步长
>>> numbers[0:10:2] 将从起点和终点之间每隔一个元素提取一个元素
[1, 3, 5, 7, 9]
当然,步长不能为0,否则无法向前移动,但可以为负数,即从右向左提取元素。
>>> numbers[10:0:-2]
[10, 8, 6, 4, 2]
>>> numbers[0:10:-2]
[]
>>> numbers[::-2]
[10, 8, 6, 4, 2]

{ 注意区分以下:
>>> numbers[5::-2]
[6, 4, 2]
>>> numbers[:5:-2]
[10, 8]
}
步长为负数时,第一个索引必须比第二个索引大。步长为正数时,它从起点移到终点,而 步长为负数时,它从终点移到起点。

2.2.3序列相加
可使用加法运算符来拼接序列。
>>> [1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]
>>> 'Hello,' + 'world!'
'Hello, world!'
提示:不能拼接列表和字符串,一般而言,不能拼接不同类型的序列
2.2.4 乘法
将序列与数x相乘时,将重复这个序列x次来创建一个新序列:
>>> [42] * 10
[42, 42, 42, 42, 42, 42, 42, 42, 42, 42]
在Python中表达‘什么都没有’可使用None
代码 序列(字符串)乘法运算示例
# 在位于屏幕中央且宽度合适的方框内打印一个句子
sentence = input("Sentence: ")

screen_width = 80
text_width = len(sentence)
box_width = text_width + 6
left_margin = (screen_width - box_width) // 2

print()
print(' ' * left_margin + '+' + '-' * (box_width-2) + '+')
print(' ' * left_margin + '| ' + ' ' * text_width + ' |')
print(' ' * left_margin + '| ' + sentence + ' |')
print(' ' * left_margin + '| ' + ' ' * text_width + ' |')
print(' ' * left_margin + '+' + '-' * (box_width-2) + '+')
print()

再有3天就过年了。。。。。

猜你喜欢

转载自www.cnblogs.com/nmlwh/p/10346822.html