<p>您可以使用<a href="https://docs.python.org/2/reference/expressions.html#in" rel="nofollow">^{<cd1>}-operator</a>来确定子字符串是否包含在另一个字符串中)。在</p>
<blockquote>
<p>For the Unicode and string types, <code>x in y</code> is true if and only if <code>x</code> is a substring of <code>y</code>. An equivalent test is <code>y.find(x) != -1</code>. [...] Empty strings are always considered to be a substring of any other string, so <code>"" in "abc"</code> will return <code>True</code>.</p>
</blockquote>
<p>您可以使用它来实现关键字排序键。在</p>
<p>您将使用另一个答案中给出的方法(将元组作为键传递)来实现作为次键的字母排序。在</p>
<p>下面是一个例子:</p>
<pre><code>import pprint
# Define the keywords I want to see first
preferred_projects = ['one', 'two', 'three']
# example data
AllMyProjectsFromaDatasource = [{ 'name': 'project two', 'id': 5, 'otherkey': 'othervalue'},
{ 'name': 'project three', 'id': 1, 'otherkey': 'othervalue'},
{ 'name': 'project one', 'id': 3, 'otherkey': 'othervalue'},
{ 'name': 'abc project', 'id': 6, 'otherkey': 'othervalue'},
{ 'name': 'one project', 'id': 9, 'otherkey': 'othervalue'}
]
def keyfunc(x):
# keyword primary key
# (add index to list comprehension when keyword is in name)
preferred_key = [float(idx)
for idx, i in enumerate(preferred_projects)
if i in x['name']]
# found at least one match in preferred keywords, use first if any, else infinity
keyword_sortkey = preferred_key[0] if preferred_key else float('inf')
# return tuple to sort according to primary and secondary key
return keyword_sortkey, x['name']
AllMyProjectsFromaDatasource.sort(key=keyfunc)
pprint.pprint(AllMyProjectsFromaDatasource)
</code></pre>
<p>输出为:</p>
^{pr2}$