482. License Key Formatting(分组操作)

本文介绍在Python中如何高效地对列表进行分组操作,提供了三种不同的实现方法,并详细解释了每种方法的工作原理及适用场景。同时展示了如何利用Python特性简化代码。

482. License Key Formatting

题目

在这里插入图片描述

对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) 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值