繁体   English   中英

使用for循环创建元组列表

[英]creating a list of tuples using for loop

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

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

使用enumerate列表理解,您可以更轻松地完成此操作:

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

所有这些功能的文档都可以在这里找到。


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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM