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

那年仲夏 提交于 2019-11-29 08:40:56

问题


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

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

What is the fastest way in python (running on a very low cpu/ram machine) to swap values like this...

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

curently using:

for x in mylist:
    self.maynewlist.append((_(x[1]),(x[0])))

Is there a better or faster way???


回答1:


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




回答2:


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.




回答3:


A fancy way:

[t[::-1] for t in mylist]



回答4:


Using a list comprehension I find more elegant and understandable to use separate variables instead of indices for a single variable as in the solution provided by @iabdalkader:

[(b, a) for a, b in mylist]


来源:https://stackoverflow.com/questions/13384841/swap-values-in-a-tuple-list-inside-a-list-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!