[英]How to pair strings inside a list?
我有一個字符串列表,我想以這樣的方式將它們配對,使得倒數第二和倒數第二對是一對,倒數第二和倒數第三是一對,依此類推,中間有三個點。
假設我有以下清單
['a', 'b', 'c', 'd', 'e']
我想把它轉換成這樣的東西
['e...d', 'd...c', 'c...b', 'b...a', 'a...none']
到目前為止,我已經完成了以下工作,
>>> import string
>>>
>>> letters = string.ascii_lowercase[:5]
>>> letters = iter(reversed(letters))
>>> pair_iter = (c + '...' + next(letters, 'none') for c in letters)
>>> pair_iter = list(pair_iter)
>>> pair_iter
['e...d', 'c...b', 'a...none']
我不確定在這種情況next
還要做什么,我確實知道next
轉到下一個字符串,但是我應該如何復制前一個然后再轉到下一個字符串?
像這樣的理解:
list(reversed(['{}..{}'.format(a, b) for a, b in zip(s, ['none'] + s[:-1])]))
s = ['a', 'b', 'c', 'd', 'e']
print(list(reversed(['{}..{}'.format(a, b) for a, b in zip(s, ['none'] + s[:-1])])))
['e..d', 'd..c', 'c..b', 'b..a', 'a..none']
您也可以增量使用索引:
s = ['a', 'b', 'c', 'd', 'e']
new_s = s[::-1]
final_s = ['{}..{}'.format(new_s[i], new_s[i+1]) for i in range(len(new_s)-1)]+['{}..{}'.format(new_s[-1], 'none')]
輸出:
['e..d', 'd..c', 'c..b', 'b..a', 'a..none']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.