调用子函数时传入基础对象的可行性及内联实现临时列表排序返回的方法咨询
Hey there! Let's walk through this step by step. First, great catch on why your original code failed—list.sort() is an in-place sorting method, which means it modifies the list it's called on directly and returns None instead of the sorted list. That's exactly why passing its result to print() gave you nothing useful.
Your two working solutions are solid:
- Method 1 using
sorted()is the most Pythonic approach here. It accepts any iterable (like your set) and returns a brand new sorted list, making it perfect for inline printing without extra steps. - Method 2 works too, though it's a bit verbose unless you have a specific need for a custom sort function. Quick note: there's a small typo in your call—you wrote
print(mysetsort(s))but should passmysetinstead ofs!
Now to your main question: Can you use sort() on the temporary inline list and still return the sorted version?
Yes, you can pull this off with a couple of tricks, though they're not as clean as using sorted(). Here are a few options:
Option 1: Using the walrus operator (Python 3.8+)
This lets you assign the temporary list, sort it, and return it all in one line:
myset = set(["A", "C", "B"]) # Inline sort with walrus operator print(temp_list if (temp_list := list(myset)).sort() is None else temp_list)
The walrus (:=) creates temp_list from your set, we call sort() on it (which returns None), then we just return the now-sorted temp_list.
Option 2: List comprehension hack (works in all Python versions)
If you can't use the walrus operator, you can use a quick list comp trick to capture the sorted list:
myset = set(["A", "C", "B"]) # Inline sort without walrus print([l for l in [list(myset)] if l.sort() is None][0])
We wrap the temporary list in another list, sort it (the if clause just lets us run the sort() method), then grab the first (and only) element which is the sorted list.
That said, I'd strongly recommend sticking with sorted(myset) for readability. Other developers looking at your code will immediately understand what's happening, whereas the inline sort() tricks are clever but not as intuitive.
备注:内容来源于stack exchange,提问作者Jules

