Python 使用for循环创建元组列表
我想从列表和列表中每个元素的位置创建一个元组列表。这就是我正在尝试的Python 使用for循环创建元组列表,python,list,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)] 使用以下工具,您可以更轻松地执行此操作: 您也可以考虑使用 xLange, Le< ,和 zip
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)]
使用以下工具,您可以更轻松地执行此操作:
您也可以考虑使用<代码> xLange,<代码> Le< <代码>,和<代码> zip < /C> > @ 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
演示:
请格式化您的代码,使其正确阅读(突出显示代码,然后单击看起来像
{}
)的按钮更简洁:zip(lis,itertools.count())
@augurar,无需使用itertoolszip(lis,xrange(len(lis))
@padraickenningham-很好!我将把它纳入我的答案中。:)@iCodez,我试过那些方法。我想使用函数-好吧,请看我的编辑。但是请注意,我给出的前两个解决方案将更加有效。
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)]
>>>