1. D:\>python
  2. Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
  3. Type "help", "copyright", "credits" or "license" for more information.
  4. #2.1序列概览
  5. >>> edward=['Edward Gumby', 42]
  6. >>> john=['John Smith',50]
  7. >>> database=[edward,john]
  8. >>> database
  9. [['Edward Gumby', 42], ['John Smith', 50]]
  10. #2.2通用序列操作
  11. #2.2.1索引
  12. #代码清单2-1索引演示样例
  13. >>> greeting='Hello'
  14. >>> greeting[0]
  15. 'H'
  16. >>> greeting[-1]
  17. 'o'
  18. >>> 'hello'[1]
  19. 'e'
  20. >>> fourth=raw_input('Year: ')[3]
  21. Year: 2005
  22. >>> fourth
  23. '5'
  24. #2.2.2分片/切片
  25. >>> tag = '<a href="http://www.python.org">Python web site</a>'
  26. >>> tag[9:30]
  27. 'http://www.python.org'
  28. >>> tag[32:-4]
  29. 'Python web site'
  30. >>> numbers = [1,2,3,4,5,6,7,8,9,10]
  31. >>> numbers[3,6]
  32. Traceback (most recent call last):
  33. File "<stdin>", line 1, in <module>
  34. TypeError: list indices must be integers, not tuple
  35. >>> numbers[3:6]
  36. [4, 5, 6]
  37. >>> numbers[0:1]
  38. [1]
  39. # 1. 优雅的捷径
  40. >>> numbers[7:10]
  41. [8, 9, 10]
  42. >>> numbers[-3:-1]
  43. [8, 9]
  44. >>> numbers[-3:0]
  45. []
  46. >>> numbers[-3:]
  47. [8, 9, 10]
  48. >>> numbers[:3]
  49. [1, 2, 3]
  50. >>> numbers[:]
  51. [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  52. #代码清单2-2 分片演示样例
  53. #2.更大的步长
  54. >>> numbers[0:10:1]
  55. [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  56. >>> numbers[0:10:2]
  57. [1, 3, 5, 7, 9]
  58. >>> numbers[3:6:3]
  59. [4]
  60. >>> numbers[::4]
  61. [1, 5, 9]
  62. >>> numbers[8:3:-1]
  63. [9, 8, 7, 6, 5]
  64. >>> numbers[8:3:1]
  65. []
  66. >>> numbers[8:3:+1]
  67. []
  68. >>> numbers[10:0:-2]
  69. [10, 8, 6, 4, 2]
  70. >>> numbers[9:0:-2]
  71. [10, 8, 6, 4, 2]
  72. >>> numbers[11:0:-2]
  73. [10, 8, 6, 4, 2]
  74. >>> numbers[0:10:-2]
  75. []
  76. >>> numbers[::-2]
  77. [10, 8, 6, 4, 2]
  78. >>> numbers[5::-2]
  79. [6, 4, 2]
  80. >>> numbers[0:5:-2]
  81. []
  82. >>> numbers[0:5:2]
  83. [1, 3, 5]
  84. >>> numbers[:5:-2]
  85. [10, 8]
  86. #2.2.3序列相加
  87. >>> [1,2,3]+[4,5,6]
  88. [1, 2, 3, 4, 5, 6]
  89. >>> 'Hello, ' + 'world'
  90. 'Hello, world'
  91. >>> [1,2,3] + 'world!'
  92. Traceback (most recent call last):
  93. File "<stdin>", line 1, in <module>
  94. TypeError: can only concatenate list (not "str") to list
  95. #2.2.4乘法
  96. >>> 'python' * 5
  97. 'pythonpythonpythonpythonpython'
  98. >>> 5 * 'python'
  99. 'pythonpythonpythonpythonpython'
  100. >>> [42] * 10
  101. [42, 42, 42, 42, 42, 42, 42, 42, 42, 42]
  102. # None, 空列表和初始化
  103. #代码清单2-3 序列(字符串)乘法演示样例
  104. >>> [0] * 10
  105. [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
  106. >>> sequence = [None] * 10
  107. >>> sequence
  108. [None, None, None, None, None, None, None, None, None, None]
  109. #2.2.5 成员资格
  110. #代码清单2-4 序列成员资格演示样例
  111. >>> permissions = 'rw'
  112. >>> 'w' in permissions
  113. True
  114. >>> 'x' in permissions
  115. False
  116. >>> users = ['mlh','foo','bar']
  117. >>> raw_input('Enter your user name: ') in users
  118. Enter your user name: mlh
  119. True
  120. >>> subject = '$$$ Get rich now! $$$'
  121. >>> '$$$' in subject
  122. True
  123. >>> 'P' in 'Python'
  124. True
  125. #2.2.6 长度, 最小值和最大值
  126. >>> numbers=[100,34,678]
  127. >>> len(numbers)
  128. 3
  129. >>> max(numbers)
  130. 678
  131. >>> min(numbers)
  132. 34
  133. >>> max(2,3)
  134. 3
  135. >>> min(9,3,2,5)
  136. 2
  137. #2.3 列表: Python的"苦力"
  138. # 列表不同于元组和字符串的地方:列表是可变的(mutable)
  139. >>> list('Hello')
  140. ['H', 'e', 'l', 'l', 'o']
  141. >>> somelist=list('Hello')
  142. >>> ''.join(somelist)
  143. 'Hello'
  144. #2.3.2主要的列表操作
  145. #1.改变列表:元素赋值
  146. >>> x=[1,1,1]
  147. >>> x[1]=2
  148. >>> x
  149. [1, 2, 1]
  150. #2.删除元素
  151. >>> names=['Alice','Beth','Cecil','Dee-Dee','Earl']
  152. >>> del names[2]
  153. >>> names
  154. ['Alice', 'Beth', 'Dee-Dee', 'Earl']
  155. #3.分片赋值/切片赋值
  156. >>> name=list('Perl')
  157. >>> name
  158. ['P', 'e', 'r', 'l']
  159. >>> name[2:]=list('ar')
  160. >>> name
  161. ['P', 'e', 'a', 'r']
  162. >>> name = list('Perl')
  163. >>> name[1:]=list('ython')
  164. >>> name
  165. ['P', 'y', 't', 'h', 'o', 'n']
  166. >>> numbers=[1,5]
  167. >>> numbers[1:1] = [2,3,5]
  168. >>> numbers
  169. [1, 2, 3, 5, 5]
  170. >>> numbers
  171. [1, 2, 3, 5, 5]
  172. >>> numbers[1:4] = []
  173. >>> numbers
  174. [1, 5]
  175. #2.3.3 列表的方法
  176. #1.append
  177. >>> lst = [1,2,3]
  178. >>> lst.append(4)
  179. >>> lst
  180. [1, 2, 3, 4]
  181. >>> ['to','be','or','not','to','be'].count('to')
  182. 2
  183. #2.count
  184. >>> x = [[1,2],1,1,[2,1,[1,2]]]
  185. >>> x.count(1)
  186. 2
  187. >>> x.count([1,2])
  188. 1
  189. #3.extend
  190. >>> a = [1,2,3]
  191. >>> b = [4,5,6]
  192. >>> a.extend(b)
  193. >>> a
  194. [1, 2, 3, 4, 5, 6]
  195. >>> b
  196. [4, 5, 6]
  197. >>> a = [1,2,3]
  198. >>> b = [4,5,6]
  199. >>> a + b
  200. [1, 2, 3, 4, 5, 6]
  201. >>> a
  202. [1, 2, 3]
  203. >>> a = a + b
  204. >>> a
  205. [1, 2, 3, 4, 5, 6]
  206. >>> a = [1,2,3]
  207. >>> b = [4,5,6]
  208. >>> a[len(a):]=b
  209. >>> a
  210. [1, 2, 3, 4, 5, 6]
  211. #4.index
  212. >>> knights = ['We','are','the','knights','who','say','ni']
  213. >>> knights.index('who')
  214. 4
  215. >>> knights.index('herring')
  216. Traceback (most recent call last):
  217. File "<stdin>", line 1, in <module>
  218. ValueError: 'herring' is not in list
  219. >>> knights[4]
  220. 'who'
  221. #5.insert
  222. >>> numbers = [1,2,3,5,6,7]
  223. >>> numbers.insert(3,'four')
  224. >>> numbers
  225. [1, 2, 3, 'four', 5, 6, 7]
  226. >>> numbers = [1,2,3,5,6,7]
  227. >>> numbers[3:3] = ['four']
  228. >>> numbers
  229. [1, 2, 3, 'four', 5, 6, 7]
  230. #6.pop
  231. >>> x = [1,2,3]
  232. >>> x.pop()
  233. 3
  234. >>> x
  235. [1, 2]
  236. >>> x.pop(0)
  237. 1
  238. >>> x
  239. [2]
  240. >>> x = [1,2,3]
  241. >>> x.append(x.pop())
  242. >>> x
  243. [1, 2, 3]
  244. #7.remove
  245. >>> x=['to','be','or','not','to','be']
  246. >>> x.remove('be')
  247. >>> x
  248. ['to', 'or', 'not', 'to', 'be']
  249. >>> x.remove('bee')
  250. Traceback (most recent call last):
  251. File "<stdin>", line 1, in <module>
  252. ValueError: list.remove(x): x not in list
  253. >>>
  254. Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
  255. Type "copyright", "credits" or "license()" for more information.
  256. #8.reverse
  257. >>> x = [1,2,3]
  258. >>> x.reverse()
  259. >>> x
  260. [3, 2, 1]
  261. >>> x = [1,2,3]
  262. >>> type(reversed(x))
  263. <type 'listreverseiterator'>
  264. >>> list(reversed(x))
  265. [3, 2, 1]
  266. #9.sort
  267. >>> x = [4,6,2,1,7,9]
  268. >>> x
  269. [4, 6, 2, 1, 7, 9]
  270. >>> x.sort()
  271. >>> x
  272. [1, 2, 4, 6, 7, 9]
  273. >>> x = [4,6,2,1,7,9]
  274. >>> y = x.sort() # Don't do this!
  275. >>> print y
  276. None
  277. >>> x = [4,6,2,1,7,9]
  278. >>> y = x
  279. >>> y
  280. [4, 6, 2, 1, 7, 9]
  281. >>> y = x[:]
  282. >>> y
  283. [4, 6, 2, 1, 7, 9]
  284. >>> y.sort()
  285. >>> x
  286. [4, 6, 2, 1, 7, 9]
  287. >>> y
  288. [1, 2, 4, 6, 7, 9]
  289. >>> x
  290. [4, 6, 2, 1, 7, 9]
  291. >>> y=x
  292. >>> x
  293. [4, 6, 2, 1, 7, 9]
  294. >>> y
  295. [4, 6, 2, 1, 7, 9]
  296. >>> y.sort()
  297. >>> x
  298. [1, 2, 4, 6, 7, 9]
  299. >>> y
  300. [1, 2, 4, 6, 7, 9]
  301. >>> x=[4,6,2,1,7,9]
  302. >>> y = sorted(x)
  303. >>> x
  304. [4, 6, 2, 1, 7, 9]
  305. >>> y
  306. [1, 2, 4, 6, 7, 9]
  307. >>> sorted('Python')
  308. ['P', 'h', 'n', 'o', 't', 'y']
  309. #10.高级排序
  310. >>> cmp(42,32)
  311. 1
  312. >>> cmp(99,100)
  313. -1
  314. >>> cmp(10,10)
  315. 0
  316. >>> numbers = [5,2,9,7]
  317. >>> numbers.sort(cmp)
  318. >>> numbers
  319. [2, 5, 7, 9]
  320. >>> x = ['aardvark','abalone','acme','add','aerate']
  321. >>> x.sort(key=len)
  322. >>> x
  323. ['add', 'acme', 'aerate', 'abalone', 'aardvark']
  324. >>> x = [4,6,2,1,7,9]
  325. >>> x.sort(reverse=True)
  326. >>> x
  327. [9, 7, 6, 4, 2, 1]
  328. #2.4 元组:不可变序列
  329. >>> 1,2,3
  330. (1, 2, 3)
  331. >>> (1,2,3)
  332. (1, 2, 3)
  333. >>> ()
  334. ()
  335. >>> 42
  336. 42
  337. >>> 42,
  338. (42,)
  339. >>> (42,)
  340. (42,)
  341. >>> 3*(40+2)
  342. 126
  343. >>> 3*(40+2,)
  344. (42, 42, 42)
  345. #2.4.1 tuple函数
  346. >>> tuple([1,2,3])
  347. (1, 2, 3)
  348. >>> tuple('abc')
  349. ('a', 'b', 'c')
  350. >>> tuple((1,2,3))
  351. (1, 2, 3)
  352. #2.4.2 基本元组操作
  353. >>> x = 1,2,3
  354. >>> x[1]
  355. 2
  356. >>> x[0:2]
  357. (1, 2)
  358. >>>
  359. #2.4.3 那么,意义何在
  360. #1.元组能够在映射(和集合的成员)中当做键使用,而列表则不行
  361. #2.元组作为非常多内建函数和方法的返回值存在,也就是说你必须对元组进行处理.
  362. #2.5小结
  363. #序列. 序列是一种数据结构, 它包括的元素都进行了编号(从0開始). 典型的序列包括列表, 字符串和元组. 当中, 列表是可变的(能够进行改动),而元组和字符串是不可变的
  364. #(一旦创建了就是固定的). 通过分片操作能够訪问序列的一部分,当中分片须要两个索引號来指出分片的起始和结束位置. 要想改变列表, 则要对对应的位置进行赋值,或
  365. #使用赋值语句重写整个分片.
  366. #成员资格 in操作符能够检查一个值是否存在于序列(或其它的容器)中. 对字符串使用in操作符是一个特例--它能够查找子字符串.
  367. #方法. 一些内建类型(比如列表和字符串, 元组则不在当中)具有非常多实用的方法. 这些方法有些像函数--只是它们与特定值联系得更密切.方法是面向对象编程的一个重要
  368. #概念.
  369.  
  370. # 本章的新函数
  371. #cmp(x,y) 比較两个值
  372. #len(seq) 返回序列的长度
  373. #list(seq) 把序列转换成列表
  374. #max(args) 返回序列或參数集合中的最大值
  375. #min(args) 返回序列或參数集合中的最小值
  376. #reversed(seq) 对序列进行反向迭代
  377. #sorted(seq) 返回已排序的包括seq全部元素的列表
  378. #tuple(seq) 把序列转换为元组
  379.  
  380. #2.5.2 接下来学什么
  381. # 序列已经介绍完了, 下一章会继续介绍由字符组成的序列,即字符串.

代码清单2-1索引演示样例

  1. #!/usr/bin/env python
  2. #encoding=utf-8
  3. months = [
  4. 'January',
  5. 'February',
  6. 'March',
  7. 'April',
  8. 'May',
  9. 'June',
  10. 'July',
  11. 'August',
  12. 'September',
  13. 'October',
  14. 'November',
  15. 'December'
  16. ]
  17. # 以1-31的数字作为结尾的列表
  18. endings = ['st','nd','rd'] + 17 * ['th'] \
  19. + ['st','nd','rd'] + 7 * ['th'] \
  20. + ['st']
  21.  
  22. year = raw_input('Year: ')
  23. month = raw_input('Month(1-12): ')
  24. day = raw_input('Day(1-31): ')
  25.  
  26. month_number = int(month)
  27. day_number = int(day)
  28.  
  29. #记得要将月份和天数减1,以获得正确的索引
  30. month_name = months[month_number-1]
  31. ordinal = day + endings[day_number-1]
  32.  
  33. print month_name + ' ' + ordinal + ', ' + year
  34.  
  35. #python e2-1.py
  36. #Year: 1981
  37. #Month(1-12): 1
  38. #Day(1-31): 1
  39. #January 1st, 1981

代码清单2-2 分片演示样例

  1. #encoding=utf8
  2. #对http://www.something.com形式的URL进行切割
  3. url = raw_input('Please enter the URL: ')
  4. domain = url[11:-4]
  5.  
  6. print "Domain name: " + domain
  7.  
  8. #python e2-2.py
  9. #Please enter the URL: http://www.python.org
  10. #Domain name: python

代码清单2-3 序列(字符串)乘法演示样例

  1. #encoding=utf-8
  2. #以正确的宽度在居中的"盒子"内打印一个句子
  3. #注意,整数除法运算(//)仅仅能用在Python2.2以及兴许版本号,在之前的版本号中,仅仅使用普通除法(/)
  4.  
  5. sentence = raw_input("Sentence: ")
  6.  
  7. screen_width = 80
  8. text_width = len(sentence)
  9. box_width = text_width + 6
  10. left_margin = (screen_width - box_width) // 2
  11.  
  12. print
  13. print ' ' * left_margin + '+' + '-' * (box_width-2) + '+'
  14. print ' ' * left_margin + '|' + ' ' * (box_width-2) + '|'
  15. print ' ' * left_margin + '|' + ' ' * 2 + sentence + ' ' * 2 + '|'
  16. print ' ' * left_margin + '|' + ' ' * (box_width-2) + '|'
  17. print ' ' * left_margin + '+' + '-' * (box_width-2) + '+'
  18. print
  19.  
  20. #python e2-3.py
  21. #Sentence: He's a very naughty boy!
  22. #
  23. # +----------------------------+
  24. # | |
  25. # | He's a very naughty boy! |
  26. # | |
  27. # +----------------------------+
  28. #

代码清单2-4 序列成员资格演示样例

  1. #encoding=utf-8
  2. database = [
  3. ['albert','1234'],
  4. ['dilbert','4242'],
  5. ['smith','7524'],
  6. ['jones','9843'],
  7. ['jonathan','6400']
  8. ]
  9. username = raw_input('User name: ')
  10. pin = raw_input('PIN code: ')
  11.  
  12. if [username, pin] in database: print 'Access granted'
  13.  
  14. #python e2-4.py
  15. #User name: jonathan
  16. #PIN code: 6400
  17. #Access granted

Python基础教程之第2章 列表和元组的更多相关文章

  1. Python基础教程之第5章 条件, 循环和其它语句

    Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32 #Chapter 5 条件, 循环 ...

  2. Python基础教程之第3章 使用字符串

    Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32 Type "copyri ...

  3. Python基础教程之第1章 基础知识

    #1.1 安装Python #1.1.1 Windows #1.1.2 Linux和UNIX #1.1.3 Macintosh #1.1.4 其它公布版 #1.1.5 时常关注.保持更新 #1.2 交 ...

  4. Python基础教程之List对象 转

    Python基础教程之List对象 时间:2014-01-19    来源:服务器之家    投稿:root   1.PyListObject对象typedef struct {    PyObjec ...

  5. Python基础教程之udp和tcp协议介绍

    Python基础教程之udp和tcp协议介绍 UDP介绍 UDP --- 用户数据报协议,是一个无连接的简单的面向数据报的运输层协议.UDP不提供可靠性,它只是把应用程序传给IP层的数据报发送出去,但 ...

  6. python基础之数字、字符串、列表、元组、字典

    Python基础二: 1.运算符: 判断某个东西是否在某个东西里面包含: in  为真 not in  为假 (1).算术运算符: 运算符 描述 实例 + 加  表示两个对象相加 a + b输出结果3 ...

  7. python 基础学习笔记(3)--列表与元组

    **本次笔记主要内容为 列表,元组主要的功能和特性** **1.列表**: 学习过c语言的同学应该知道,c语言有数组这一功能,就是将数据类型相同的元素放在一起.由于python的变量没有数据类型,也就 ...

  8. Python基础灬序列(字符串、列表、元组)

    序列 序列是指它的成员都是有序排列,并且可以通过下标偏移量访问到它的一个或几个成员.序列包含字符串.列表.元组. 字符串 chinese_zodiac = '鼠牛虎兔龙蛇马羊猴鸡狗猪' print(c ...

  9. python基础教程之pymongo库

    1. 引入 在这里我们来看一下Python3下MongoDB的存储操作,在本节开始之前请确保你已经安装好了MongoDB并启动了其服务,另外安装好了Python的PyMongo库. 1.  安装 pi ...

随机推荐

  1. SQL 教程学习进度备忘

    书签:跳过:另外跳过的内容有待跟进 __________________ 学习资源:W3School. _________________ 跳过的内容: 1.  “SQL select”底部的“ AD ...

  2. 【LeetCode】190 & 191 - Reverse Bits & Number of 1 Bits

    190 - Reverse Bits Reverse bits of a given 32 bits unsigned integer. For example, given input 432615 ...

  3. xcode XCTest录制后测试出错临时解决方法

    Xcode 使用 XCTest 做自动化测试,录制后在run UITest 的时候总是莫名报错,后来在方法执行前添加sleep()后,没有再出现错误,可能是xcode的一处BUG.

  4. HDU-3872 Dragon Ball 线段树+DP

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3872 题意:有n个龙珠按顺序放在一列,每个龙珠有一个type和一个权值,要求你把这n个龙珠分成k个段, ...

  5. 【转】webgame前台开发总结--虽然是10年的文章,但是也有参考价值

    一.webgame整个游戏流程: 1.预加载(打开游戏页面后,显示进度条,主要加载前期的登陆和创建角色资源,创建角色资源的加载可以放到进入创建角色界面的时候加载,因为玩家除了第一次进入游戏,其他时间基 ...

  6. tomcat 粗略笔记

    GlobalNamingResources 存在于server.xml中,定义全局公共数据源,如果host中有大量引用相同的数据源,那么可以都配在这里 <GlobalNamingResource ...

  7. Jenkins+Gitlab搭建持续集成(CI)环境

    利用Jenkins+Gitlab搭建持续集成(CI)环境 Permalink: 2013-09-08 22:04:00 by hyhx2008in intern tags: jenkins gitla ...

  8. CTE初识

    微软从SQl2005起引入了CTE(Common Table Expression)以强化T-SQL.这是一个类似于非持久视图的好东西. 正常的SQL语句: select * from person. ...

  9. Thinkphp模板怎么使用自定义函数

    内置模板引擎支持对模板变量使用函数,并支持多个函数同时使用. 注意:自定义函数要放在项目应用目录/common/common.php中. 这里是关键. 模板变量的函数调用格式:{$varname|fu ...

  10. Ehcache详细解读

    [http://raychase.iteye.com/blog/1545906]   Ehcache 是现在最流行的纯Java开源缓存框架. [通过编程方式使用EhCache ]   //从class ...