You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python初学者请求解释对称差集求解代码及key作用

解释对称差集代码与key的作用

Hey there! Let's break this down nice and slow since you're a Python beginner—no fancy jargon, just straight-up explanations.

First, let's start with the full code snippet (I'll fill in the condensed parts you mentioned):

# 跳过两个集合的长度输入(因为我们直接读取元素行即可)
for _ in range(2):
    raw_input()
# 读取两行元素输入并转换为集合
a, b = [set(raw_input().split()) for _ in range(2)]
# 计算两个集合的对称差集
symmetric_diff = a.symmetric_difference(b)
# 按整数规则排序并输出结果
sorted_result = sorted(symmetric_diff, key=int)
print(' '.join(sorted_result))

Or if the code skipped the length lines entirely (since input lengths don't affect set creation), it might look even more concise:

a, b = [set(raw_input().split()) for _ in range(2)]
print(' '.join(sorted(a ^ b, key=int)))

逐行拆解代码逻辑

Let's use your input example to walk through each step:

  • 读取输入: raw_input().split() takes a line of input (like "2 4 5 9") and splits it into a list of strings: ["2", "4", "5", "9"]. Wrapping this in set() converts the list to a Python set, which automatically handles duplicate values (though your input probably has no duplicates anyway).
  • 计算对称差集: a.symmetric_difference(b) (or the shorthand a ^ b) gives us elements that exist in either set a or set b, but not in both. For your example, this results in {"5", "9", "11", "12"}—exactly the elements you need for the output.
  • 排序处理: sorted(symmetric_diff, key=int) is where the critical part happens. Since our set elements are strings (from the split() method), sorting them directly would use dictionary order (e.g., "11" would come before "5" because '1' has a lower ASCII value than '5'). Using key=int tells Python to convert each string element to an integer first, then sort based on those integer values.
  • 输出结果: ' '.join(sorted_result) converts the sorted list of strings back into a single space-separated string, matching your expected output: "5 9 11 12".

key参数的核心作用是什么?

The key parameter in functions like sorted() (or the list method sort()) lets you define a custom rule for how elements should be sorted. Here's the basic breakdown:

  • By default, Python sorts elements using their natural order: strings use dictionary order, numbers use numeric order, etc.
  • When you pass key=some_function, Python runs some_function on every element first, then sorts the original elements based on the result of that function.
  • In our case, key=int means: take each string element (like "5"), convert it to an integer (5), then sort the original elements using those integer values. That's why we get the correct numeric order instead of the wonky string-based order.

更多key的示例帮你理解:

  • 按字符串长度排序:sorted(["apple", "banana", "cherry"], key=len) → ["apple", "cherry", "banana"]
  • 按元组的第二个元素排序:sorted([(1,3), (2,1), (3,2)], key=lambda x: x[1]) → [(2,1), (3,2), (1,3)]

和你原来方法的对比

Your approach using a long for loop and adding elements to a set works perfectly fine—this code just leverages Python's built-in set operations to do the same thing in fewer lines. Sets in Python are optimized for membership checks and operations like symmetric difference, so this method is also more efficient under the hood.

内容的提问来源于stack exchange,提问作者Riya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:52:04