我有一个元组列表,如下所示:
lst = [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')]
我想得到:
list = [('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')]
我相信这很简单,但不幸的是我被卡住了..
任何帮助将非常感激。
这是一种方法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 也是一个好主意。编辑:基于下面的评论 - 修复了“错误”(跳过一些组合) - 将 var “list” 更改为 “myList”
只需清理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()
. 这会更快。
试试下面的方法
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')]