我有这个案子:
list = ["Translate:(0,0,0)", "Scale:(1,1,1)", "Rotate:(0,180,0)"]
str = "Rotate:"
我想基于传入的字符串str对此列表进行排序,在这种情况下是“旋转:”,因此包含“旋转:”的项目将转到列表中的第一个位置。我不关心其余元素的顺序。像这样:
["Rotate:(0,180,0)", "Scale:(1,1,1)", "Translate:(0,0,0)"]
是否可以通过key = lambda ...
使用“已排序”功能等等或cmp
来实现?
或者我必须做更复杂的循环和比较来重建列表?
答案 0 :(得分:2)
使用str_ in x
作为密钥:
>>> list_ = ["Translate:(0,0,0)","Scale:(1,1,1)", "Rotate:(0,180,0)"]
>>> str_ = "Rotate:"
>>> sorted(list_, key=lambda x:str_ in x, reverse=True)
['Rotate:(0,180,0)', 'Translate:(0,0,0)', 'Scale:(1,1,1)']
答案 1 :(得分:1)
def bring_to_front(lst, match_str):
"""
Given a list of strings and a match string,
return a copy of the list with all items
beginning with match_str moved to the head of the list
"""
return sorted(lst, key = lambda s: s.startswith(match_str), reverse=True)
然后
>>> lst = ["Translate:(0,0,0)", "Rotate:(0,0,90)", "Scale:(1,1,1)", "Rotate:(0,180,0)"]
>>> bring_to_front(lst, "Rotate:")
['Rotate:(0,0,90)', 'Rotate:(0,180,0)', 'Translate:(0,0,0)', 'Scale:(1,1,1)']
答案 2 :(得分:0)
if "Rot" in word: # "Rotate()" returns True
liste.remove(word) # remove the word
liste.insert(0, word) # insert it again as first position