[英]sorted() function affects the original list
I am testing some sorting algorithms by passing a list of strings to them.我正在通过将字符串列表传递给它们来测试一些排序算法。 the structure is like this:结构是这样的:
def test(test_case):
ans = sorted(test_case)
for f in functs:
assert f(test_case) == ans
However, I found that test_case
is changing all the time (I call test()
for once).但是,我发现test_case
一直在变化(我调用test()
一次)。 There is a time I passed ["Test", "String']
to test()
and I put print()
in my f
to catch the input. I found that f
received [("Test", "String'), ("Test", "String'), ("Test", "String'), ("Test", "String'), ("Test", "String'), ...]
.有一次我将["Test", "String']
传递给test()
并将print()
放入我的f
中以捕获输入。我发现f
收到[("Test", "String'), ("Test", "String'), ("Test", "String'), ("Test", "String'), ("Test", "String'), ...]
。 May I know why this happened and what is the solution for that?我可以知道为什么会发生这种情况以及解决方案是什么吗?
sorted
does not affect your original list (ie, it does not sort the list in place), but if you execute the code on the interactive interpreter the output of sorted
is going to be printed. sorted
不会影响您的原始列表(即,它不会对列表进行适当的排序),但如果您在交互式解释器上执行代码,则会打印sorted
的 output。
So what you see is the list sorted, followed by the original list.所以你看到的是排序后的列表,然后是原始列表。
['a', 'day', 'for', 'have', 'nice', 'reading', 'thanks']
['thanks', 'for', 'reading', 'have', 'a', 'nice', 'day']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.