加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 使用for循环创建元组列表

发布时间:2020-12-20 11:40:09 所属栏目:Python 来源:网络整理
导读:我想从列表中的每个元素的列表和位置创建元组列表.这是我正在尝试的. 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)] 解决方法 使
我想从列表中的每个元素的列表和位置创建元组列表.这是我正在尝试的.

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和 list comprehension可以更轻松地完成此操作:

>>> lis=[1,5]
>>> [(x,i) for i,x in enumerate(lis)]
[(1,4)]
>>>

您可能还会考虑使用xrange,len和zip作为@PadraicCunningham提议:

>>> lis=[1,5]
>>> zip(lis,xrange(len(lis))) # Call list() on this in Python 3
[(1,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,5]
>>> func_(lis)
[(1,4)]
>>>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读