python - 如何在 Python 列表中切换两个项目的位置?

我在网上一直没能找到很好的解决这个问题的办法(可能是因为switch、position、list和python都是这么重载的词)。

这很简单——我有这个 list :

['title', 'email', 'password2', 'password1', 'first_name', 'last_name', 'next', 'newsletter']

我想切换 'password2''password1' 的位置 - 不知道它们的确切位置,只知道它们彼此相邻并且password2 是第一位的。

我已经通过一些冗长的列表下标实现了这一点,但我想知道它是否可以想出一些更优雅的东西?

最佳答案

i = ['title', 'email', 'password2', 'password1', 'first_name', 
     'last_name', 'next', 'newsletter']
a, b = i.index('password2'), i.index('password1')
i[b], i[a] = i[a], i[b]

https://stackoverflow.com/questions/2493920/

相关文章:

linux - 对标准输入、标准输出和标准错误感到困惑?

linux - 如何在 Minikube 中使用本地 docker 镜像?

python - python - 如何按两列或多列对python pandas中的dataFram

linux - fork()、vfork()、exec()和clone()的区别

python - 如何避免 "RuntimeError: dictionary changed si

python - 如何比较 Python 中的版本号?

linux - 遍历带有空格的文件列表

python - 将 numpy dtypes 转换为原生 python 类型

python - 错误 : command 'gcc' failed with exit statu

Android Debug Bridge (adb) 设备 - 无权限