擅长:python、mysql、java
<p>举个例子:假设您想按每个集合的“第一个元素”对集合列表进行排序。问题是Python集或frozensets没有“第一个元素”,它们没有自己的顺序感。集合是没有重复元素的无序集合。在</p>
<p>此外,<code>list.sort()</code>对列表进行适当排序,<a href="https://docs.python.org/3/library/stdtypes.html#list.sort" rel="nofollow noreferrer">using only the ^{<cd2>} operator between items</a>。在</p>
<p>如果您只使用<code>a.sort()</code>而不传递任何<code>key</code>参数,那么说<code>set_a < set_b</code>(或<code>set_a.__lt__(set_b)</code>)是<em>不够的</em>。我的意思是<code>set_a.__lt__(set_b)</code>是一个<em>子集</em>运算符。(<code>a</code>是<code>b</code>的子集吗?)。正如@Blender提到的,在你的问题中提到的,这提供了部分而不是全部的排序,这不足以定义序列中包含的集合。在</p>
<p>从文件中:</p>
<blockquote>
<p><code>set < other</code>: Test whether the set is a proper subset of other, that
is, <code>set <= other</code> and <code>set != other</code>.</p>
</blockquote>
<p>你可以把一个<code>key</code>传递给<code>sort()</code>,它只是不能在内部引用任何与集合的“排序”有关的内容,因为记住没有。在</p>
<pre><code>>>> a = {2, 3, 1}
>>> b = {6, 9, 0, 1}
>>> c = {0}
>>> i = [b, a, c]
>>> i.sort(key=len)
>>> i
[{0}, {1, 2, 3}, {0, 9, 6, 1}]
</code></pre>