当前位置: 代码迷 >> python >> 将字符串拆分为固定数量的令牌的简便方法
  详细解决方案

将字符串拆分为固定数量的令牌的简便方法

热度:93   发布时间:2023-06-19 09:33:40.0

我正在编写一段代码,该代码需要将连字符分隔的字符串最多拆分为三个标记。 如果拆分后少于三个令牌,则应附加足够数量的空字符串以生成三个令牌。

例如,应将'foo-bar-baz'拆分为['foo', 'bar', 'baz'] ,但是将foo-bar拆分为['foo', 'bar', '']

这是我写的代码。

def three_tokens(s):
    tokens = s.split('-', 2)
    if len(tokens) == 1:
        tokens.append('')
        tokens.append('')
    elif len(tokens) == 2:
        tokens.append('')
    return tokens

print(three_tokens(''))
print(three_tokens('foo'))
print(three_tokens('foo-bar'))
print(three_tokens('foo-bar-baz'))
print(three_tokens('foo-bar-baz-qux'))

这是输出:

['', '', '']
['foo', '', '']
['foo', 'bar', '']
['foo', 'bar', 'baz']
['foo', 'bar', 'baz-qux']

我的问题是,对于这个小任务,我编写的three_tokens函数似乎过于冗长。 是否有Python方式来编写此代码,或者是否有某些Python函数或类专门用于执行此类使代码更简洁的任务?

您可以使用一个简单的while循环:

def three_tokens(s):
    tokens = s.split('-', 2)
    while len(tokens) < 3:
        tokens.append('')
    return tokens

或使用计算出的空字符串数扩展列表:

def three_tokens(s):
    tokens = s.split('-', 2)
    tokens.extend([''] * (3 - len(tokens)))
    return tokens

或使用串联,以便将其放入return语句中:

def three_tokens(s):
    tokens = s.split('-', 2)
    return tokens + [''] * (3 - len(tokens))

可能有些itertools ,但是您可以使用itertools的一些方法。

list(itertools.islice(itertools.chain(s.split('-', 2), itertools.repeat('')), 3)

使用 :

def three_tokens(s):
    t1, unused, t2 = s.partition('-')
    t2, unused, t3 = t2.partition('-')
    return [t1, t2, t3]

这可能有效。

tokens = s.split('-', 2)
tokens += [''] * max(0, 3 - len(tokens))
>>> n = 3
>>> a = '123-abc'
>>> b = a.split('-', n)
>>> if len(b) < n-1:
...     b = b + ['']*(n-len(b))
...
>>> b
['123', 'abc', '']
>>>
def three_tokens(s):
    tokens = s.split('-', 2)
    return [tokens.pop(0) if len(tokens) else '' for _ in range(0, 3)]

...产量

>>> three_tokens('foo')
['foo', '', '']

>>> three_tokens('foo-bar')
['foo', 'bar', '']

>>> three_tokens('foo-bar-baz')
['foo', 'bar', 'baz']

>>> three_tokens('foo-bar-baz-buzz')
['foo', 'bar', 'baz-buzz']

这个怎么样?

def three_tokens(s):
    output = ['', '', '']
    tokens = s.split('-', 2)
    output[0:len(tokens)] = tokens
    return output

另外一个oneliner:

three_tokens = lambda s: (s.split('-', 2) + ['', ''])[:3]

顺便说一句,我在您的解决方案中找不到任何非Python的东西。 这有点冗长,但目的很明确。

多一个:

def three_tokens(s):
   it = iter(s.split('-', 2))
   return [ next(it, '') for _ in range(3) ]
  相关解决方案