需要对给定的字符串进行排序(字符串以x开头)
问题描述:
当给出['mix', 'xyz', 'apple', 'xanadu', 'aardvark']
列表时,代码不返回最后一个字。需要对给定的字符串进行排序(字符串以x开头)
def front_x(words):
x_list = []
no_x_list = []
[x_list.append(i) for i in words if i[0] == "x"]
[no_x_list.append(words[i2]) for i2 in range(len(words)-1) if words[i2] not in x_list]
x_list.sort()
no_x_list.sort()
return x_list + no_x_list
print front_x(['mix', 'xyz', 'apple', 'xanadu', 'aardvark'])
必须是:
['xanadu', 'xyz', 'aardvark', 'apple', 'mix']
随着名单['bbb', 'ccc', 'axx', 'xzz', 'xaa']
和['ccc', 'bbb', 'aaa', 'xcc', 'xaa']
一切是正确的['xaa', 'xzz', 'axx', 'bbb', 'ccc']
和['xaa', 'xcc', 'aaa', 'bbb', 'ccc']
答
对range(len(words)-1)
的迭代看起来不正确。更多的是,使列表附加列表理解是相当unpythonic; list comps是用于建立不使列表附加的列表,而这是讽刺这里。
您可以通过基于二元组进行排序来进行一次排序,该二元组的第一项检查单词以'x'
开头并将其放在前面。在数组中的第二项施加lexicograhical排序名单上,打破关系:
def front_x(words):
return sorted(words, key=lambda y: (not y.startswith('x'), y))
print front_x(['mix', 'xyz', 'apple', 'xanadu', 'aardvark'])
# ['xanadu', 'xyz', 'aardvark', 'apple', 'mix']
答
你可以试试这个:
words = ['mix', 'xyz', 'apple', 'xanadu', 'aardvark']
new_words = [i for i in words if i[0].lower() == "x"]
words = [i for i in words if i[0].lower() != "x"]
final_words = sorted(new_words)+sorted(words)
print(final_words)
输出:
['xanadu', 'xyz', 'aardvark', 'apple', 'mix']
答
只需卸下-1从range(len(words)-1)
这将是你的代码的最小变化。
答
您必须使用len(words)
而不是len(words)-1
才能获得预期的输出。
所以,试试这个方法:
def front_x(words):
x_list = []
no_x_list = []
[x_list.append(i) for i in words if i[0] == "x"]
[no_x_list.append(words[i2]) for i2 in range(len(words)) if words[i2] not in x_list]
x_list.sort()
no_x_list.sort()
return x_list + no_x_list
print front_x(['mix', 'xyz', 'apple', 'xanadu', 'aardvark'])
输出:
['xanadu', 'xyz', 'aardvark', 'apple', 'mix']
这是一个简单的重复回答 – Cuber
@Cuber,如何???? –
应该是一个编辑 –