【问题标题】:grouping a list into sublists, breaked by alphabet elements in python将列表分组为子列表,由python中的字母元素分隔
【发布时间】:2018-09-16 14:47:55
【问题描述】:

我在 python 中有一个混合列表:有些元素是数字,有些是字母。

例如:l = ['999','123','hello','222','333','444','bye']

我想将此列表拆分为由所有字母元素分隔的列表:

['999','123','hello'], ['222','333','444','bye']

对于['hello', '123', 'test', 'test', '456', 'test', '789'] 输出将是:['hello'],['123','test'],['test'],['456','test'],['789']

每个元素都是字母或数字。

最pythonic的方法是什么?

【问题讨论】:

  • 如果您在输入的末尾有一个额外的bye...第二个列表输出是否也会有额外的bye 或其他内容?
  • 那么当你遇到任何包含至少一个非数字符号的字符串时,你想拆分吗?
  • @JonClements - 是的
  • @oren_isp ['hello', '123', 'test', 'test', '456', 'test', '789'] 会是什么?
  • @not_a_bot_no_really_82353 - 是的,但最好以最pythonic和最快的方式,因为我必须检查大量数据

标签: python regex string python-3.x list


【解决方案1】:
output = []
for i in l:
    if not output or output[-1][-1].isalpha():
        output.append([i])
    else:
        output[-1].append(i)

这样:

l = ['999','123','hello','222','333','444','bye']

output 会变成:

[['999', '123', 'hello'], ['222', '333', '444', 'bye']]

或与:

l = ['hello', '123', 'test', 'test', '456', 'test', '789']

output 将变为:

[['hello'], ['123', 'test'], ['test'], ['456', 'test'], ['789']]

【讨论】:

  • 我不确定它是否正确 - 对于 ['dress', '9239307', 'sheer', 'pants'] 我得到的是 ['dress', '9239307', 'sheer'],['pants'] 而不是 ['dress'], ['9239307', 'sheer'],['pants']
  • 我只是复制并粘贴了这个输入并自己尝试了一下,我得到了[['dress'], ['9239307', 'sheer'], ['pants']] 作为输出。请确保您的输入在您的测试中是正确的。
猜你喜欢
  • 2019-04-08
  • 1970-01-01
  • 2017-04-11
  • 1970-01-01
  • 2015-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-27
相关资源
最近更新 更多