如何为任何给定列表切换元素? [英] How to switch elements for any given list?
问题描述
我说我有一个列表:["5", "6", "4", "3"]
我想做的是用"6"
替换任何字符"5"
并用"5"
替换"6"
.
What I want to do is replace any char "5"
with "6"
and replace "6"
with "5"
.
所以列表最后看起来像这样:
So the list would look like this in the end:
["6", "5", "4", "3"]
我要对可能输入的所有列表执行此操作.这意味着并非所有列表中都将包含元素"5"
和"6"
,但是我想为执行此操作的列表切换5
和6
.
I want to do this for all lists that may be inputted. This means that not all lists will have the elements "5"
and "6"
in them, but I want to switch the 5
's and the 6
's for the lists that do.
注意:列表中的元素是字符串元素.不是整数.
Note: The elements in the list are string elements. Not integers.
我一直在考虑使用if
语句和.replace()
,但这会更改5
和6
,但随后又将其更改回去.
I've been thinking of using if
statements and .replace()
but that changes the 5
and 6
, but then changes it back.
示例:
if "5" in list1:
list1.replace("5", "6")
if "6" in list1:
list1.replace("6", "5")
如您所见,这只是将其替换回来.它不起作用.如果有人可以帮助我解决这个问题,那就太好了.
As you can see, that just replaces it back. It doesn't work. It would be great if someone could help me solve this.
注意:如果元素在列表中为"1532"
,则该元素中的5
也应替换为字符串.反之亦然.
Note: If the element is "1532"
in a list, the 5
in that should also be replaced with a string. Vice versa for 6
's as well.
另一个示例:
firstlist = ["125", "673", "222", "65"]`
输出:
firstlist = ["126", "573", "222", "56"]
推荐答案
在假设列表中没有下划线和制表符的情况下,这可以起作用:
Under the assumption there are no underscores and tabs in your lists, this can work:
>>> list1 = ["126", "573", "222", "56"]
>>> str1 = "\t".join(list1)
>>> str1.replace("5", "_").replace("6", "5").replace("_", "6").split('\t')
['125', '673', '222', '65']
这篇关于如何为任何给定列表切换元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!