Python中列表经函数处理后转集合失效及两种写法差异咨询
Why Your Two Approaches Produce Different Results
Hey there! The key issue here all boils down to one critical detail about Python's set type: sets are unordered collections. Let's break down exactly what each approach does step by step to see why you're getting such different outputs.
First Approach: set(sorted([2*t for t in B], reverse=True))
Let's walk through the operations in order:
- List comprehension: Creates a new list where every element in
Bis multiplied by 2. For yourBexample, this gives[4, 6, 8, 10, 14, 132, 112, 68, 44, 690, 44, 6, 10]. - Sort in reverse: Sorts this list from largest to smallest, resulting in
[690, 132, 112, 68, 44, 44, 14, 10, 10, 8, 6, 6, 4]. - Convert to set: Here's the problem! When you convert an ordered sequence (like the sorted list) to a
set, Python discards all order information. Sets are built for fast membership checks and deduplication—not preserving order. The set will remove duplicates, but its elements will be stored in an arbitrary order (determined by hash values), which is why your print output looks jumbled.
Second Approach: sorted(set([2*t for t in B]), reverse=True)
Now let's look at this working version:
- List comprehension: Same as before, we get
[4, 6, 8, 10, 14, 132, 112, 68, 44, 690, 44, 6, 10]. - Convert to set: This removes duplicates, giving us an unordered set
{4, 6, 8, 10, 14, 44, 68, 112, 132, 690}. - Sort in reverse: The
sorted()function takes any iterable (including an unordered set) and returns a new ordered list sorted according to your criteria. Since we're sorting after converting to a set, the order is preserved in the final list output—exactly what you wanted!
Quick Recap of the Core Difference
- First approach: Sorts first, then loses order when converting to a set.
- Second approach: Removes duplicates first with a set, then sorts the result to get an ordered list.
Remember: In standard Python, sets never maintain insertion or sorted order. If you ever need a deduplicated collection that keeps order, you'd use something like dict.fromkeys() (which preserves insertion order in Python 3.7+) or a third-party OrderedSet—but for your use case, sorting after deduplication is the perfect fix.
内容的提问来源于stack exchange,提问作者rachit saini
相关产品推荐
相关产品推荐

