【问题标题】:python 2.7.5+ split list ['a', 'xxx yyy zzz'] into list ['a', 'xxx', 'yyy', 'zzz'] how?python 2.7.5+ 拆分列表 ['a', 'xxx yyy zzz'] 成列表 ['a', 'xxx', 'yyy', 'zzz'] 如何?
【发布时间】:2014-02-09 13:20:13
【问题描述】:

如何拆分

list = ['a', 'xxx yyy zzz']

进入

list = ['a', 'xxx', 'yyy', 'zzz']

在 Python 2.7.5+ 中(默认,2013 年 9 月 19 日,13:48:49)[GCC 4.8.1] on linux2)?

试过了

...
for i in range(0, len(list)):
    list[i] = list[i].split(' ')
...

但没有结果。

【问题讨论】:

  • 分割的标准究竟是什么?在空白处拆分?分成 3 个字符或更少的部分? ...
  • 嗨卢卡斯。它在例如之间的空间分裂字符串 xxx 和字符串 yyy。感谢您的反应 ;-)

标签: python string list split


【解决方案1】:

你可以用列表理解来做到这一点,像这样

my_list = ['a', 'xxx yyy zzz']
print [word for words in my_list for word in words.split()]

输出

['a', 'xxx', 'yyy', 'zzz']

建议:永远不要将变量命名为list,因为它会影响内置的list 函数

【讨论】:

  • 只是在问题的上下文中将其命名为“列表”;-) 别担心,我不会在实际代码中这样做。感谢您的反应。
  • @user1614113 很高兴你已经知道了 :) 如果对你有帮助,请考虑 accepting this answer
【解决方案2】:

一种快速而肮脏的方法是:

l = ['a', 'xxx yyy zzz']
l = " ".join(l).split()

更好的是:

l = ['a', 'xxx yyy zzz']
l = sum((s.split() for s in l), [])

【讨论】:

    【解决方案3】:

    另一个使用map和未绑定方法str.split的解决方案:

    >>> lst = ['a', 'xxx yyy zzz']
    >>> sum(map(str.split, lst), [])
    ['a', 'xxx', 'yyy', 'zzz']
    
    >>> from itertools import chain
    >>> list(chain.from_iterable(map(str.split, lst)))
    ['a', 'xxx', 'yyy', 'zzz']
    

    【讨论】:

      【解决方案4】:
      >>> [word for s in L for word in s.split()]
      ['a', 'xxx', 'yyy', 'zzz']
      

      【讨论】:

        猜你喜欢
        • 2011-08-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-21
        相关资源
        最近更新 更多