2013-09-27 67 views
0

我有以下代码,并想知道是否有一个更简单的方法来做到这一点。 我正在创建一个元组列表,它包含字符串中的字母和列表中相应的数字。这里是压缩代码或一个可能的代码python的代码

s="hello" 
lst=[1,2,3,4,5] 
res = [] 
for i in range(len(lst)): 
    res.append((s[i],lst[i])) 
print res 

输出在这里是正确的。我在找精简版如果可能的话

[('h', 1), ('e', 2), ('l', 3), ('l', 4), ('o', 5)] 
+1

尝试: 'zip(s,lst)' –

+1

你也可以尝试:'map(None,s,list)',但是对于'zip()'更具语义。 –

回答

7

如何:

>>> s = "hello" 
>>> lst = [1, 2, 3, 4, 5] 
>>> zip(s, lst) 
[('h', 1), ('e', 2), ('l', 3), ('l', 4), ('o', 5)] 

注意,这里自列表和字符串长度相等的工作。否则,您可能会截断。

编辑:

>>> s = "hell" 
>>> lst = [1, 2, 3, 4, 5] 
>>> zip(s, lst) 
[('h', 1), ('e', 2), ('l', 3), ('l', 4)] 

你有lst的最后一个项目错过了。

+0

截断是什么意思? – eagertoLearn

+0

@ user2708477尝试:'zip('abc',[1,2,3,4])' –

+0

@ user2708477:see my edit – eagertoLearn

5

使用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)] 
2

这是zip一个单元:

>>> s="hello" 
>>> lst=[1,2,3,4,5] 
>>> zip(s, lst) 
[('h', 1), ('e', 2), ('l', 3), ('l', 4), ('o', 5)] 
>>> 

请注意,我在Python 2.x中写了这在Python 3.x中,你需要这样做:

>>> s="hello" 
>>> lst=[1,2,3,4,5] 
>>> zip(s, lst) 
<zip object at 0x021C36C0> 
>>> list(zip(s, lst)) 
[('h', 1), ('e', 2), ('l', 3), ('l', 4), ('o', 5)] 
>>> 

这是因为,作为demonstarted,Python的3.x的像它在Python 2.x版本做zip返回一个zip对象而不是列表

2

我不知道,如果该列表是永远只是单调的数字,但如果是这样,您可以用范围(替换),或使用枚举做这一行:

s = 'hello' 
sd = dict([reversed(x) for x in enumerate(s)]) 

s = 'hello' 
zip(s, xrange(len(s))) 
+0

btw,'[x [ :-1] for enumerate(s)]'既短又快,通常比reverse()快,出于某种原因... –