>>> x = [1, 2, 3, ‘p‘ , ‘y‘] >>> for v in x: ... print(x) ... 1 2 3 p y
>>> y = {‘a‘:11, ‘b‘:22} >>> y {‘b‘: 22, ‘a‘: 11} >>> for v in y: ... print(v) ... b a >>> for v in y.keys(): ... print(v) ... b a >>> for v in y.values(): ... print(v) ... 22 11 >>> for v in y.items(): ... print(v) ... (‘b‘, 22) (‘a‘, 11)
>>> x [1, 2, 3] >>> y {‘c‘, ‘b‘, ‘a‘} >>> for i, j in zip(x, y): # 用i,j分别遍历容器x和y中的元素,一旦其中某个容器遍历结束循环终止。 ... print(i, j) ... 1 c 2 b 3 a >>> z = (5, 6, 7) >>> for i,j,k in zip(x,y,z): # 同时遍历三个容器 ... print(i, j, k) ... 1 c 5 2 b 6 3 a 7
获取 1-10的逆序序列 >>> for i in reversed(range(10)): ... print(i+1, end = ‘ ‘) ... 10 9 8 7 6 5 4 3 2 1 获取有序的字符序列 >>> for c in sorted(‘hello world‘): ... print(c, end = ‘ ‘) ... d e h l l l o o r w 去除重复数据 >>> for x in set([1,1,2,2,2,3,3]): ... print(x, end = ‘ ‘) ... 1 2 3
>>> word = [‘a‘, ‘b‘, ‘c‘] >>> for v in word[:]: ... word.append(‘q‘) ... >>> word [‘a‘, ‘b‘, ‘c‘, ‘q‘, ‘q‘, ‘q‘]
参考:
[1] Python3.4 帮助文档
https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences
原文:http://blog.csdn.net/xiaohui_hubei/article/details/25060421