# python学习笔记02--列表和元组

## 二、使用

dotgua = ['dotgua', 24]

### 通用序列操作

#### √ 索引

>>> dotgua = ['dotgua', 24]
>>> dotgua[0]
'dotgua'


>>> dotgua[-1]
24


>>> 'dotgua'[2]
't'


#!/usr/bin/env python
# 根据给定的年月日以数字形式打印出日期
months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
]

# 以1~31的数字作为结尾的列表
endings = ['st', 'nd', 'rd'] + 17 * ['th'] + \
['st', 'nd', 'rd'] + 7 * ['th'] + ['st']

year = input('Year: ')
month = input('Month(1-12): ')
day = input('Day(1-31): ')

month_number = int(month)
day_number = int(day)

# 将月份和天数减1获得正确的索引
month_name = months[month_number-1]
ordinal = day + endings[day_number-1]

print(month_name + ' ' + ordinal + ', ' + year)


#### √ 分片

>>> numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> numbers[2:4]
[2, 3]


>>> numbers[-3:-1]
[7, 8]


>>> numbers[-3:]
[7, 8, 9]


>>> numbers[:3]
[0, 1, 2]


>>> numbers[:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]


>>> numbers[0:10:2]
[0, 2, 4, 6, 8]


>>> numbers[10:0:-3]
[9, 6, 3]


#### √ 序列相加

>>> [1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]


#### √ 序列乘法

>>> 'python' * 5
'pythonpythonpythonpythonpython'
>>> [4] * 10
[4, 4, 4, 4, 4, 4, 4, 4, 4, 4]


>>> seq = [None]*10
>>> seq
[None, None, None, None, None, None, None, None, None, None]


#### √ 成员资格

>>> 5 in numbers
True


database = [
['dotgua', '1234'],
['dotdai', '4567'],
]
print('Access granted')
else:
print('Not granted')


#### √ 长度、最大值和最小值

len()返回序列的长度

max()返回序列的最大值

min()返回序列的最小值

>>> len(numbers)
10
>>> max(numbers)
9
>>> min(numbers)
0


## 三、列表

### 1. list函数

list函数可以将字符串转化为单个字符的列表：

>>> list('dotgua')
['d', 'o', 't', 'g', 'u', 'a']

join可以执行相反操作：

''.join(['d', 'o', 't', 'g', 'u', 'a'])

### 2. 基本操作

#### 删除元素

>>> del numbers[2]
>>> numbers
[0, 1, 3, 4, 5, 6, 7, 8, 9]

#### 分片赋值

>>> numbers = [1, 2, 3]
>>> numbers[3:] = [4, 5, 6]
>>> numbers
[1, 2, 3, 4, 5, 6]

>>> numbers = [1, 2, 3]
>>> numbers[1:] = [4, 5, 6]
>>> numbers
[1, 4, 5, 6]

>>> numbers[1:] = []
>>> numbers
[1]


### 3. 列表方法

#### pop

remove

posted @ 2016-12-06 15:44  dotgua  阅读(350)  评论(0编辑  收藏  举报