簡體   English   中英

在python中壓縮該代碼或一個可能的襯里

[英]condensing the code or a one liner possible for this code in 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)]

這個怎么樣:

>>> 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錯過了。

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

這是因為,正如所演示的那樣,Python 3.x zip返回的是zip對象,而不是像Python 2.x中那樣的列表。

我不知道列表是否總是單調的數字,但是如果是單調的數字,則可以將其替換為range(),也可以使用enumerate使其成為一行:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM