Python - 将字符串拆分为列表列表中的单词

时间:2017-10-25 09:36:02

标签: python list split python-2.x

我有以下列表列表():

[[u' why not giving me service'], [u' option to'], [u' removing an'], [u' verify name and '], [u' my credit card'], [u' credit card'], [u' theres something on my visa']]

我有以下问题: 首先,这些u'出现在我的每个子列表面前是什么? 其次,我如何将我的子列表分成单独的单词,即具有以下内容:

 [[why, not, giving, me, service], [option, to], [removing, an], [verify, name, and], [my, credit, card], [credit, card], [theres, something, on, my, visa]]

我已经尝试了split函数,但收到以下错误消息:AttributeError: 'list' object has no attribute 'split' Thanx很多。

3 个答案:

答案 0 :(得分:2)

使用str.split()功能:

l = [[u' why not giving me service'], [u' option to'], [u' removing an'], [u' verify name and '], [u' my credit card'], [u' credit card'], [u' theres something on my visa']]

result = [_[0].split() for _ in l]
print(result)

输出:

[['why', 'not', 'giving', 'me', 'service'], ['option', 'to'], ['removing', 'an'], ['verify', 'name', 'and'], ['my', 'credit', 'card'], ['credit', 'card'], ['theres', 'something', 'on', 'my', 'visa']]

答案 1 :(得分:0)

代码:

list_1 = [[u' why not giving me service'], [u' option to'], [u' removing an'], [u' verify name and '], [u' my credit card'], [u' credit card'], [u' theres something on my visa']]
res = []
for list in list_1:
    res.append(str(list[0]).split())

print res

输出:

[['why', 'not', 'giving', 'me', 'service'], ['option', 'to'], ['removing', 'an'], ['verify', 'name', 'and'], ['my', 'credit', 'card'], ['credit', 'card'], ['theres', 'something', 'on', 'my', 'visa']]

你'代表unicode,我希望这能回答你的问题

答案 2 :(得分:0)

x=[[u' why not giving me service'], [u' option to'], [u' removing an'], [u' verify name and '], [u' my credit card'], [u' credit card'], [u' theres something on my visa']]
[[y.split() for y in m] for m in x]

这是它的输出:

In [3]: [[y.split() for y in m] for m in x]
Out[3]: 
[[[u'why', u'not', u'giving', u'me', u'service']],
 [[u'option', u'to']],
 [[u'removing', u'an']],
 [[u'verify', u'name', u'and']],
 [[u'my', u'credit', u'card']],
 [[u'credit', u'card']],
 [[u'theres', u'something', u'on', u'my', u'visa']]]