代码之家  ›  专栏  ›  技术社区  ›  Vondoe79

python-如何从单个列表中创建元组列表[重复]

  •  1
  • Vondoe79  · 技术社区  · 7 年前

    B_tuple_list = [(3,2), (2,1), (1,0), (0,5), (5,4)] A_python_list = [3, 2, 1, 0, 5, 4]

    谢谢您。

    5 回复  |  直到 7 年前
        1
  •  1
  •   Austin    7 年前

    zip

    a_list = [3, 2, 1, 0, 5, 4]
    tuple_list = [(x, y) for x, y in zip(a_list, a_list[1:])]
    
    # [(3, 2), (2, 1), (1, 0), (0, 5), (5, 4)]
    

    tuple_list = list(zip(a_list, a_list[1:]))
    
        2
  •  3
  •   Patrick Haugh    7 年前

    您也可以使用 zip

    l = [3, 2, 1, 0, 5, 4]
    print(list(zip(l, l[1:])))
    # [(3, 2), (2, 1), (1, 0), (0, 5), (5, 4)]
    
        3
  •  3
  •   niraj    7 年前

    list comprehension 以下内容:

    a_list = [3, 2, 1, 0, 5, 4]
    tuple_list = [(a_list[i], a_list[i+1]) for i in range(len(a_list)-1)]
    print(tuple_list)
    

    [(3, 2), (2, 1), (1, 0), (0, 5), (5, 4)]
    
        4
  •  2
  •   Olivier Melançon iacob    7 年前

    itertools recipes

    from itertools import tee
    
    def pairwise(iterable):
        a, b = tee(iterable)
        next(b, None)
        return list(zip(a, b))
    
    print(pairwise([1, 2, 3, 4])) # [(1, 2), (2, 3), (3, 4)]
    

    list

        5
  •  1
  •   jowabels    7 年前

    >>> a = [3, 2, 1, 0, 5, 4]
    >>> b = [(a[x], a[x+1]) for x in range(len(a))]
    >>> print b
    [(3, 2), (2, 1), (1, 0), (0, 5), (5, 4)]