简体   繁体   English

sorted() function 影响原始列表

[英]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.

相关问题 Python:对列表副本进行切片会在使用嵌套的for循环时影响原始的元组或列表 - Python: slicing a list copy affects the original tuple or list when using nested for loops 如何在 Python 中创建 function 以确定列表是否已排序? - How to create a function in Python to determine if list is sorted or not? 递归 function 检查元素是否在 SORTED 列表中 - A recursive function to check if element is in SORTED list 如何对传递给 function 的原始数组进行排序,我们在 function 中使用“Sorted( )”函数。 在 Python - How to sort the original array passed to a function, Where we use the "Sorted( )" funtion inside the function. In Python Python; 原始列表在函数内更改 - python; original list changing within function 使用排序功能对列表的嵌套列表进行排序。 - Sorting nested list of list using sorted function.? python - 通过字符串匹配将列表排序到嵌套列表中,无需排序 function - python - Sort a list into a nested list by string match without sorted function 如果列表已排序,我必须创建一个返回 True 或 False 的函数 - I have to create a function that returns True or False if a list is sorted 创建一个函数genSet(),该函数接受一个数字列表并在python中返回一个排序的集合 - Create a function genSet() that takes in a list of numbers and returns a sorted set in python function count_numbers 接受唯一整数的排序列表 - function count_numbers that accepts a sorted list of unique integers
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM