使用for循环创建元组列表

时间:2015-01-19 22:39:35

标签: python list

我想从列表中的每个元素的列表和位置创建元组列表。这是我正在尝试的。

def func_ (lis):
    ind=0
    list=[]
    for h in lis:
       print h
       return h

让我们说功能论证:

lis=[1,2,3,4,5]

我想知道如何使用ind。

期望的输出:

[(1,0),(2,1),(3,2),(4,3),(5,4)]

1 个答案:

答案 0 :(得分:7)

使用enumeratelist comprehension

,您可以轻松完成此操作
>>> lis=[1,2,3,4,5]
>>> [(x, i) for i, x in enumerate(lis)]
[(1, 0), (2, 1), (3, 2), (4, 3), (5, 4)]
>>>

您可能还会考虑使用xrangelenzip作为@PadraicCunningham提议:

>>> lis=[1,2,3,4,5]
>>> zip(lis, xrange(len(lis))) # Call list() on this in Python 3
[(1, 0), (2, 1), (3, 2), (4, 3), (5, 4)]
>>>

可以找到所有这些功能的文档here


如果您必须定义自己的功能,那么您可以执行以下操作:

def func_(lis):
    ind = 0
    lst = [] # Don't use 'list' as a name; it overshadows the built-in
    for h in lis:
        lst.append((h, ind))
        ind += 1 # Increment the index counter
    return lst

演示:

>>> def func_(lis):
...     ind = 0
...     lst = []
...     for h in lis:
...         lst.append((h, ind))
...         ind += 1
...     return lst
...
>>> lis=[1,2,3,4,5]
>>> func_(lis)
[(1, 0), (2, 1), (3, 2), (4, 3), (5, 4)]
>>>