Swap values in a tuple/list inside a list in python?

前端 未结 4 713
遥遥无期
遥遥无期 2020-12-09 11:27

I have a tuple/list inside a list like this:

[(\'foo\',\'bar\'),(\'foo1\',\'bar1\'),(\'foofoo\',\'barbar\')]

What is the fastest way in pyt

4条回答
  •  甜味超标
    2020-12-09 11:37

    You could use map:

    map (lambda t: (t[1], t[0]), mylist)
    

    Or list comprehension:

    [(t[1], t[0]) for t in mylist]
    

    List comprehensions are preferred and supposedly much faster than map when lambda is needed, however note that list comprehension has a strict evaluation, that is it will be evaluated as soon as it gets bound to variable, if you're worried about memory consumption use a generator instead:

    g = ((t[1], t[0]) for t in mylist)
    #call when you need a value
    g.next()
    

    There are some more details here: Python List Comprehension Vs. Map

提交回复
热议问题