使用zip()
功能:
該函數返回的元組,其中第i元組包含來自每個參數的第i個元素的列表序列或迭代。
演示:
>>> s="hello"
>>> lst=[1,2,3,4,5]
>>>
>>> zip(s, lst)
[('h', 1), ('e', 2), ('l', 3), ('l', 4), ('o', 5)]
需要注意的是,在Python 3.x中,zip()
返回迭代器。您必須將返回值包含在list(zip(s, lst))
中,以使其成爲一個列表。
要在Python 2.x中獲得迭代器,請使用itertools.izip()
。另外,如果序列的長度不相等,則可以使用itertools.izip_longest()
。
>>> s="hell" # len(s) < len(lst)
>>> lst=[1,2,3,4,5]
>>>
>>> zip(s, lst) # Iterates till the length of smallest sequence
[('h', 1), ('e', 2), ('l', 3), ('l', 4)]
>>>
>>> from itertools import izip_longest
>>> list(izip_longest(s, lst, fillvalue='-'))
[('h', 1), ('e', 2), ('l', 3), ('l', 4), ('-', 5)]
嘗試: 'zip(s,lst)' –
你也可以嘗試:'map(None,s,list)',但是對於'zip()'更具語義。 –