![](/img/trans.png)
[英]regular expression match a string 'xxx(yyy) (zzz(qqq))' or 'xxx(yyy)'
[英]python 2.7.5+ split list ['a', 'xxx yyy zzz'] into list ['a', 'xxx', 'yyy', 'zzz'] how?
我該如何拆分
list = ['a', 'xxx yyy zzz']
成
list = ['a', 'xxx', 'yyy', 'zzz']
在Python 2.7.5+(默認,2013年9月19日,13:48:49)[Linux 4上的[GCC 4.8.1])?
它試過了
...
for i in range(0, len(list)):
list[i] = list[i].split(' ')
...
但沒有結果。
您可以使用列表理解來完成此操作
my_list = ['a', 'xxx yyy zzz']
print [word for words in my_list for word in words.split()]
產量
['a', 'xxx', 'yyy', 'zzz']
建議:永遠不要將變量命名為list
因為它會影響內置list
功能
一種快速而骯臟的方式是:
l = ['a', 'xxx yyy zzz']
l = " ".join(l).split()
更好的是:
l = ['a', 'xxx yyy zzz']
l = sum((s.split() for s in l), [])
>>> [word for s in L for word in s.split()]
['a', 'xxx', 'yyy', 'zzz']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.