将每个元组与元组列表中的下一个元组合并
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')]
我相信这很简单,但不幸的是我卡住了..
任何帮助将不胜感激。
只需清洁 python 内置:
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()
。这样会更快。
这是 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
相加。
这是我认为应该有效的方法: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 也是一个好主意。
编辑:基于以下评论
-修复了 "bug"(跳过某些组合)
-将 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)
输出:
[('a', 'b', 'c', 'd'), ('c', 'd', 'e', 'f'), ('e', 'f', 'g', 'h')]
我有一个元组列表,如下所示:
lst = [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')]
我想得到:
list = [('a', 'b', 'c', 'd'), ('c', 'd', 'e', 'f'), ('e', 'f', 'g', 'h')]
我相信这很简单,但不幸的是我卡住了..
任何帮助将不胜感激。
只需清洁 python 内置:
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()
。这样会更快。
这是 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
相加。
这是我认为应该有效的方法: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 也是一个好主意。 编辑:基于以下评论 -修复了 "bug"(跳过某些组合) -将 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)
输出:
[('a', 'b', 'c', 'd'), ('c', 'd', 'e', 'f'), ('e', 'f', 'g', 'h')]