我想从列表中的每个元素的列表和位置创建元组列表.这是我正在尝试的.
def func_ (lis):
ind=0
list=[]
for h in lis:
print h
return h
Run Code Online (Sandbox Code Playgroud)
让我们说功能论证:
lis=[1,2,3,4,5]
Run Code Online (Sandbox Code Playgroud)
我想知道如何使用ind.
期望的输出:
[(1,0),(2,1),(3,2),(4,3),(5,4)]
Run Code Online (Sandbox Code Playgroud)
>>> lis=[1,2,3,4,5]
>>> [(x, i) for i, x in enumerate(lis)]
[(1, 0), (2, 1), (3, 2), (4, 3), (5, 4)]
>>>
Run Code Online (Sandbox Code Playgroud)
你也可以考虑使用xrange,len以及zip为@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)]
>>>
Run Code Online (Sandbox Code Playgroud)
所有这些功能的文档都可以在这里找到.
如果您必须定义自己的功能,那么您可以执行以下操作:
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
Run Code Online (Sandbox Code Playgroud)
演示:
>>> 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)]
>>>
Run Code Online (Sandbox Code Playgroud)