题目
对list分组
python 中对 list 进行分组,比较常用。当然方法也很多,但有很好,很简便的方法在下面叙述。
比如:比如将 a=[1,2,3,4,5,6,7,8,9,10,11,12,13,14] 按照长度为3进行分组。
方法1:
L = [3,8,9,4,1,10,6,7,2,5]
result = [[],[],[]]
for item in L:
if len(result[0]) < 3:
result[0].append(item)
elif len(result[1]) < 3:
result[1].append(item)
else:
result[2].append(item)
print result
方法2:
a=[1,2,3,4,5,6,7,8,9,10,11,12,13,14]
for i in range(0, len(a), 3):
b.append(a[i:i+3])
print b
方法3:
print [a[i:i+3] for i in xrange(0,len(a),3)]
高效代码
跟我一开始想的差不多的方法。即用上面的方法3。但没有想到使用[::-1]处理列表。
class Solution:
def licenseKeyFormatting(self, S: str, K: int) -> str:
"""
:type S: str
:type K: int
:rtype: str
"""
S = S.replace("-", "").upper()[::-1]
return '-'.join(S[i:i+K] for i in range(0, len(S), K))[::-1]
下面使用了正向的算法,效率更高。
class Solution:
def licenseKeyFormatting(self, S: 'str', K: 'int') -> 'str':
S = S.upper().replace('-', '')
n = len(S)
head = n % K
res = [S[:head]] if head else []
for i in range(head, n, K):
res.append(S[i:i+K])
return '-'.join(res)