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

前端 未结 4 686
遥遥无期
遥遥无期 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:53

    You can use reversed like this:

    tuple(reversed((1, 2)) == (2, 1)
    

    To apply it to a list, you can use map or a list comprehension:

    map(tuple, map(reversed, tuples))     # map
    [tuple(reversed(x)) for x in tuples]  # list comprehension
    

    If you're interested primarily in runtime speed, I can only recommend that you profile the various approaches and pick the fastest.

提交回复
热议问题