有没有办法使用 lambda 表达式执行以下 python sort
操作?
sorted_urls = []
for url in all_urls:
if '/en-' in url:
sorted_urls.insert(0, url)
else:
sorted_urls.append(url)
second_sorted_urls = []
for url in sorted_urls:
if '/season-' not in url:
second_sorted_urls.insert(0, url)
else:
second_sorted_urls.append(url)
换句话说,我想按以下方式排序:'season-' not in url
ASC, 'en' in url
ASC
最佳答案
是的。元组自然按每个元素依次排序, bool 值排序 False < True
,所以只需使用 lambda 给出元组键:
sorted_urls = sorted(all_urls, key=lambda x: ('season-' in x, 'en' not in x))
bool 值被反转,因为 False
值将被排序到排序列表的开头。您还可以使用sorted(all_urls, key=lambda x: ('season-' not in x, 'en' in x), reverse=True))
.
关于python - 使用 lambda 进行复杂排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35307376/