[英]merging each tuple with the next one in a list of tuples
我有一個元組列表,如下所示:
lst = [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')]
我想得到:
list = [('a', 'b', 'c', 'd'), ('c', 'd', 'e', 'f'), ('e', 'f', 'g', 'h')]
我相信這很簡單,但不幸的是我被卡住了..
任何幫助將非常感激。
這是zip()
的一種方法:
>>> lst = [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')]
>>> [x + y for x, y in zip(lst, lst[1:])]
[('a', 'b', 'c', 'd'), ('c', 'd', 'e', 'f'), ('e', 'f', 'g', 'h')]
zip(lst, lst[1:])
將每個元素及其下一個鄰居壓縮成一個(x, y)
元組,然后我們將這些元組與x + y
一起添加。
只需清理 python builins:
old_list = [(a, b), (c, d), (e, f), (g, h)]
length_of_new_list = len(list) - 1
new_list= []
for i in range(length_of_new_list):
new_list.append(old_list [i] + old_list [i + 1])
正如 RoadRunner 所提到的,您也可以使用zip()
。 這會更快。
這是我認為應該起作用的方法:D
myList= [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')]
newList = []
for i in range(0, len(myList)-1, 1):
newList += ([myList[i] + myList[i+1]])
print(newList)
使用 zip 也是一個好主意。 編輯:基於下面的評論 - 修復了“錯誤”(跳過一些組合) - 將 var “list” 更改為 “myList”
試試下面的方法
list1 = [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')]
length = len(list1)
res = []
for i in range(length-1):
res.append(list1[i] + list1[i+1])
print(res)
output:
[('a', 'b', 'c', 'd'), ('c', 'd', 'e', 'f'), ('e', 'f', 'g', 'h')]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.