You have an array of logs
. Each log is a space delimited string of words.
For each log, the first word in each log is an alphanumeric identifier. Then, either:
- Each word after the identifier will consist only of lowercase letters, or;
- Each word after the identifier will consist only of digits.
We will call these two varieties of logs letter-logs and digit-logs. It is guaranteed that each log has at least one word after its identifier.
Reorder the logs so that all of the letter-logs come before any digit-log. The letter-logs are ordered lexicographically ignoring identifier, with the identifier used in case of ties. The digit-logs should be put in their original order.
Return the final order of the logs.
Example 1:
Input: ["a1 9 2 3 1","g1 act car","zo4 4 7","ab1 off key dog","a8 act zoo"] Output: ["g1 act car","a8 act zoo","ab1 off key dog","a1 9 2 3 1","zo4 4 7"]
思路
这种简单题,做出来挺简单,就看怎么写代码更优雅
学英语:
alphanumeric - 含有字母和数字的; 字母与数字并用的
lexicographically - 字典序的
tie - 相等;系上
代码
我的
class Solution:
def reorderLogFiles(self, logs: List[str]) -> List[str]:
letterlogs = []
digitlogs = []
for i, log in enumerate(logs):
index = log.find(' ')
if log[index + 1].isalpha():
letterlogs.append((log[index+1:], log[:index]))
else:
digitlogs.append(log)
letterlogs.sort()
return [i[1] + ' ' + i[0] for i in letterlogs] + digitlogs
官方答案
def reorderLogFiles(self, logs):
def f(log):
id_, rest = log.split(" ", 1)
return (0, rest, id_) if rest[0].isalpha() else (1,)
return sorted(logs, key = f)
原来def里还能放def,学习了。
学会一个思路,注意看这个方法的返回值。如果排序的因素有多项的时候可以用返回一个tuple的方法。通过首位0,1来安排letterlog和digitlog的排序,然后后面放rest和id。
之前觉得python3的sort取消了cmp这个参数很难搞,其实用这个方法,key也可以很强大。
学习了Python的三元表达式,很好理解的if else。