python - get list of tuples first index?

后端 未结 5 1127
隐瞒了意图╮
隐瞒了意图╮ 2020-12-03 02:48

What\'s the most compact way to return the following:

Given a list of tuples, return a list consisting of the tuples first (or second, doesn\'t matter) elements.

相关标签:
5条回答
  • 2020-12-03 03:12

    use zip if you need both

    >>> r=(1,'one'),(2,'two'),(3,'three')
    >>> zip(*r)
    [(1, 2, 3), ('one', 'two', 'three')]
    
    0 讨论(0)
  • 2020-12-03 03:12

    You can try this too..

    dict(my_list).keys()
    
    0 讨论(0)
  • 2020-12-03 03:14
    >>> mylist = [(1,'one'),(2,'two'),(3,'three')]
    >>> [j for i,j in mylist]
    ['one', 'two', 'three']
    >>> [i for i,j in mylist]
    [1, 2, 3]
    

    This is using a list comprehension (have a look at this link). So it iterates through the elements in mylist, setting i and j to the two elements in the tuple, in turn. It is effectively equivalent to:

    >>> newlist = []
    >>> for i, j in mylist:
    ...     newlist.append(i)
    ... 
    >>> newlist
    [1, 2, 3]
    
    0 讨论(0)
  • 2020-12-03 03:21
    >>> tl = [(1,'one'),(2,'two'),(3,'three')]
    >>> [item[0] for item in tl]
    [1, 2, 3]
    
    0 讨论(0)
  • 2020-12-03 03:21

    Try this.

    >>> list(map(lambda x: x[0], my_list))
    
    0 讨论(0)
提交回复
热议问题