2013-09-27 141 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()快,出於某種原因... –