【问题标题】:merging each tuple with the next one in a list of tuples将每个元组与元组列表中的下一个元组合并
【发布时间】:2020-05-10 10:38:55
【问题描述】:

我有一个如下所示的元组列表:

lst = [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')]

我想得到:

list = [('a', 'b', 'c', 'd'), ('c', 'd', 'e', 'f'), ('e', 'f', 'g', 'h')]

我相信这很简单,但不幸的是我被卡住了..

任何帮助将不胜感激。

【问题讨论】:

  • 到目前为止你尝试了什么?另外,为什么d 没有与e 合并?
  • 打错了,谢谢指正,我试过用zip,但是好像没有正确使用
  • [(a, b), (c, d), (e, f), (g, h)] -- 这不是正确的 python 代码。

标签: python python-3.x list tuples python-zip


【解决方案1】:

这是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 一起添加。

【讨论】:

    【解决方案2】:

    只需清理 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()。这样会更快。

    【讨论】:

    • 不应将列表称为list,因为它是“保留对象类型”。
    • 即使名称为 list 也能正常工作,但还是谢谢
    【解决方案3】:

    这是我认为应该起作用的: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 也是一个好主意。 编辑:基于下面的 cmets -修复了“错误”(跳过一些组合) -将 var "list" 更改为 "myList"

    【讨论】:

    • 列表不应该被称为list,它是一个对象的名称,而不是一个变量,所以它可能会造成混淆。
    • 还是不错的一个,但它给出了[('a', 'b', 'c', 'd'), ('e', 'f', 'g', 'h')],中间没有('c', 'd', 'e', 'f')
    【解决方案4】:

    按以下方式试试

    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')]
    

    【讨论】:

      猜你喜欢
      • 2022-06-15
      • 2018-08-24
      • 1970-01-01
      • 2021-11-28
      • 2021-06-15
      • 2022-08-18
      • 2013-09-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多