简体   繁体   中英

creating a list of tuples using for loop

I want to create a list of tuples from a list and position of each element in list. Here is what I am trying.

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

Let's say argument of function:

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

I was wondering how to make use if ind.

Desired output:

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

You can do this a lot easier with enumerate and a list 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)]
>>>

You might also consider using xrange , len , and zip as @PadraicCunningham proposed:

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

Documentation for all of these functions can be found here .


If you must define your own function, then you can do something like:

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

Demo:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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