【问题标题】:Python - Split strings into words within a list of listsPython - 将字符串拆分为列表列表中的单词
【发布时间】:2018-04-06 08:05:15
【问题描述】:

我有以下列表列表():

[[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' 非常感谢。

【问题讨论】:

  • u' 表示字符串是unicode。列表没有拆分方法。字符串可以。
  • 查找扁平化列表列表

标签: python list split python-2.x


【解决方案1】:

带有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']]

【讨论】:

  • 为什么要使用下划线?
  • 嗯,是的,upvoters,这非常简单,但它不考虑,例如[[u'a b c', u'd e f'], [..]] -> 内部列表中的多个字符串。
  • 有趣的是,我想知道为什么要使用下划线...你能解释一下为什么不给它一个合适的名字吗?
  • @MosesKoledoye,在这种情况下使用_ 有什么陷阱?
  • 本身没有陷阱,但通常你会将它们用于丢弃的对象。
【解决方案2】:

代码:

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']]

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

【讨论】:

    【解决方案3】:
    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']]]
    

    【讨论】:

      猜你喜欢
      • 2018-03-13
      • 2017-08-16
      • 2023-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多