1.zip()
In[30]: a Out[28]: [1, 2, 3, 4, 5] In[31]: b Out[29]: [3, 4, 5, 6, 7] In[32]: a[i]+b[i] ————————————解決該問題方法一 In[27]: c=[] In[28]: for i in range(5): ... c.append(a[i]+b[i]) ... In[29]: c Out[27]: [4, 6, 8, 10, 12]
另一個方法則為並行迭代,需要zip()函式:zip(迭代物件1,迭代物件2,迭代物件3……)--------》返回一個zip物件
In[33]: help(zip) Help on class zip in module builtins: class zip(object) | zip(iter1 [,iter2 [...]]) --> zip object | | Return a zip object whose .__next__() method returns a tuple where | the i-th element comes from the i-th iterable argument. The .__next__() | method continues until the shortest iterable in the argument sequence | is exhausted and then it raises StopIteration.
In[49]: a='abcde' In[50]: b='12345' In[51]: tuple(zip(a,b)) Out[48]: (('a', '1'), ('b', '2'), ('c', '3'), ('d', '4'), ('e', '5')) In[52]: list(zip(a,b)) Out[49]: [('a', '1'), ('b', '2'), ('c', '3'), ('d', '4'), ('e', '5')]
解決a+b問題:
In[73]: a Out[70]: [1, 2, 3, 4, 5] In[74]: b Out[71]: [3, 4, 5, 6, 7] In[75]: c=[] In[76]: for i,j in zip(a,b): ... c.append(i+j) ... In[77]: c Out[74]: [4, 6, 8, 10, 12]
2.enumerate()函式,同時得到索引和值:enumerate(可迭代物件,[開始計數值])-------->((索引1,值),(索引2,值)……)
In[83]: a='abcdefghijklmn' In[84]: b=list(enumerate(a)) In[85]: b Out[82]: #索引和值的混合輸出結果 [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g'), (7, 'h'), (8, 'i'), (9, 'j'), (10, 'k'), (11, 'l'), (12, 'm'), (13, 'n')]
In[86]: b=list(enumerate(a,start=1))
In[87]: b
Out[84]:
[(1, 'a'),
(2, 'b'),
(3, 'c'),
(4, 'd'),
(5, 'e'),
(6, 'f'),
(7, 'g'),
(8, 'h'),
(9, 'i'),
(10, 'j'),
(11, 'k'),
(12, 'l'),
(13, 'm'),
(14, 'n')]
3.列表解析:[表示式(i)for i in(可迭代物件)]
In[92]: list(range(0,100,5)) Out[89]: [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95] In[93]: i=1 In[94]: [i for i in range(0,100,5)] #100以內5的整數倍 Out[91]: [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
In[96]: [i**0.5 for i in range(10)] #10以內,每個數的平方根 Out[93]: [0.0, 1.0, 1.4142135623730951, 1.7320508075688772, 2.0, 2.23606797749979, 2.449489742783178, 2.6457513110645907, 2.8284271247461903, 3.0]