【问题标题】:Slice every string in list in Python在 Python 中切片列表中的每个字符串
【发布时间】:2016-05-20 18:52:06
【问题描述】:

我想在 Python 中对列表中的每个字符串进行切片。

这是我目前的清单:

['One', 'Two', 'Three', 'Four', 'Five']

这是我想要的结果列表:

['O', 'T', 'Thr', 'Fo', 'Fi']

我想从列表中的每个字符串中切掉最后两个字符。

我该怎么做?

【问题讨论】:

  • 在您寻求解决方案之前,请尽量展示最小的努力。
  • 你能从一个字符串中分割出最后两个字符吗?
  • 我认为我们应该通过不提供现成的解决方案来阻止这类问题,这不会真正帮助 OP,至少对他的未来没有帮助。

标签: python string list slice


【解决方案1】:

使用list comprehension 创建一个新列表,并将表达式的结果应用于输入列表中的每个元素;这里是最后两个字符的[:-2] 切片,返回余数:

[w[:-2] for w in list_of_words]

演示:

>>> list_of_words = ['One', 'Two', 'Three', 'Four', 'Five']
>>> [w[:-2] for w in list_of_words]
['O', 'T', 'Thr', 'Fo', 'Fi']

【讨论】:

    【解决方案2】:

    你可以这样做:

    >>> l = ['One', 'Two', 'Three', 'Four', 'Five'] 
    >>> [i[:-2] for i in l]
    ['O', 'T', 'Thr', 'Fo', 'Fi']
    

    【讨论】:

      【解决方案3】:
      x=['One', 'Two', 'Three', 'Four', 'Five']
      print map(lambda i:i[:-2],x)  #for python 2.7
      print list(map(lambda i:i[:-2],x)) #for python 3
      

      【讨论】:

        猜你喜欢
        • 2023-04-09
        • 1970-01-01
        • 2011-10-24
        • 1970-01-01
        • 2015-04-28
        • 1970-01-01
        • 1970-01-01
        • 2021-03-18
        • 2021-05-01
        相关资源
        最近更新 更多