使用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()'更具语义。 –