列表和元组
列表可以修改,元组不能
- 1.
>>> greeting="Hello"
>>> greeting[0]
'H'
>>> greeting[-1]
'o'
>>>
序列中所有元素都是有编号的——从零开始递增。最后一个元素的编号是-1,倒数第二个元素的编号为-2,以此类推。
- 2.
>>> fourth=raw_input("year:")[3]
year:2005
>>> fourth
'5'
根据情况直接在函数后使用索引,可直接返回相应元素。
- 3.
months=[
'January',
'Febuary',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
];
day_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):");
print months[month-1]+' '+repr(day)+day_endings[day-1]+', '+repr(year);
这个程序是根据指定的年月日打印出日期。结果如下:
>>> runfile('C:/Users/50258/.spyder2/.temp.py', wdir=r'C:/Users/50258/.spyder2')
Year:1997
Month(1-12):2
Day(1-31):3
Febuary 3rd, 1997
>>> runfile('C:/Users/50258/.spyder2/.temp.py', wdir=r'C:/Users/50258/.spyder2')
Year:2007
Month(1-12):11
Day(1-31):25
November 25th, 2007
- 4.
>>> tag='<a href="http://www.python.org">Python web site </a>'
>>> tag
'<a href="http://www.python.org">Python web site </a>'
>>> tag[9:30]
'http://www.python.org'
>>> tag[32:-4]
'Python web site '
通过分片访问一定范围内的元素。
>>> numbers=['1','2','3','4','5','6']
>>> numbers[0:1]
['1']
第一个索引是包含在分片内的,第二个索引则在分片外。
>>> numbers=['1','2','3','4','5','6']
>>> numbers[3:]
['4', '5', '6']
如果想要访问的部分包含最后一个元素,则第二个索引置空。
>>> numbers[:3]
['1', '2', '3']
>>> numbers[:]
['1', '2', '3', '4', '5', '6']
方法同样适用于开头的元素,如果想取整个序列,则两个索引都置空。
>>> numbers=['1','2','3','4','5','6','7','8','9','10']
>>> numbers[::3]
['1', '4', '7', '10']
>>> numbers[10:0:-3]
['10', '7', '4']
>>> numbers[::-3]
['10', '7', '4', '1']
这里分片的第三个参数为步长,当步长为正从左到右提取元素,步长为负从右到左提取元素。开始点的元素包括在结果之中,而结束点的元素则不在分片之中。
- 5.
sentence = raw_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
这里是一个把所输入的一段话用方块包起来的例子,用到了序列的乘法,还有“//”为整数除法运算符。
输出范例:
Sentence: What is your name?
+----------------------+
| |
| What is your name? |
| |
+----------------------+
- 6.
database = [
['albert', '1234'],
['dilbert', '4242'],
['smith', '7524'],
['jones', '9843']
]
username = raw_input('User name: ')
pin = raw_input('PIN code: ')
if [username, pin] in database:
print 'Access granted'
else:
print 'Access deny'
用户输入username和pin,与database中数据一致的输出Access granted,不一致的输出Access deny。
输出结果:
User name: albert
PIN code: 1234
Access granted
User name: abler
PIN code: 3333
Access deny