为什么不能在一行中交换列表中的两个项目? [英] Why can't I swap two items in a list in one line?

查看:45
本文介绍了为什么不能在一行中交换列表中的两个项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这为什么不起作用(值不交换):

Why does this not work (values are not swapped):

lol = ["test","test2"]
lol[lol.index("test")], lol[lol.index("test2")] = lol[lol.index("test2")], lol[lol.index("test")]

但这可行(交换值):

i1 = lol.index("test")
i2 = lol.index("test2")
lol[i1], lol[i2] = lol[i2], lol[i1]

推荐答案

第一个示例不起作用的原因是因为您多次调用.index(),并且每次之后,列表中的值都在变化,因此,在代码中找到的索引不能代表元素的实际位置.第二个示例之所以有效,是因为您已将第一个索引存储在两个变量中,并且在交换中都使用了它们.

The reason why the first example is not working is because you are calling .index() multiple times, and after each time, the values in the list are changing, so the indices found in the code are not representative of the actual locations of the elements. The second example works because you have stored the first indices in two variables, and use both in the swap.

第一个示例概述:

lol[lol.index("test")], lol[lol.index("test2")] = lol[lol.index("test2")], lol[lol.index("test")] 

第一部分:lol[lol.index("test")]存储0

第二部分:lol[lol.index("test2")]存储1

第三部分:lol[lol.index("test2")]仍存储1

这是当它变得有趣的时候.示例的第四部分lol[lol.index("test")]查找test的索引,但是,从代码的第三段中为test分配了1.因此,lol[lol.index("test")]1,而不是0.因此,lol[lol.index("test2")]仍存储1.

This is when it gets interesting. The forth part of the example, lol[lol.index("test")], finds the index of test, however, test was assigned 1 from the third segment of the code. Therefore, lol[lol.index("test")] is 1, not 0. Consequently, lol[lol.index("test2")] still stores 1.

这篇关于为什么不能在一行中交换列表中的两个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆