【问题标题】:Slicing of python os.listdir()python os.listdir() 的切片
【发布时间】:2011-06-07 19:40:29
【问题描述】:

我可以在 os.listdir() 中进行切片吗?只取一些元素。

【问题讨论】:

  • 对不起,我从 python 开始。我不认为可以像 g.d.d.c 用户那样在函数中使用“[:]”。
  • 在 Python 中,只要基于前面的返回类型有意义,您就可以链接操作。在这种情况下,os.listdir() 返回一个列表,这使得其上的切片表示法有效。如果它返回了一个生成器,那么您需要以某种方式将其转换为列表以便能够对其进行切片。
  • @g.d.d.c:我有很强的 C 语言基础,一开始要了解 python 的推理并不容易。谢谢
  • 即使没有,您也可以将结果存储在某处,然后对其进行切片。

标签: python slice


【解决方案1】:

我不明白为什么不这样做:

>>> os.listdir(os.getcwd())
['CVS', 'library.bin', 'man', 'PyLpr-0.2a.zip', 'pylpr.exe', 'python26.dll', 'text']
>>> os.listdir(os.getcwd())[3:]
['PyLpr-0.2a.zip', 'pylpr.exe', 'python26.dll', 'text']

【讨论】:

    【解决方案2】:

    由于os.listdir(path) 返回一个列表,您可以对结果使用切片表示法。例如,您可以使用os.listdir(path)[:5] 获取前 5 个结果:

    >>> import os
    >>> os.listdir('.')
    ['f1', 'f10', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9']
    >>> os.listdir('.')[:5]
    ['f1', 'f10', 'f2', 'f3', 'f4']
    

    请参阅Explain Python's slice notation 了解切片符号的全面概述。

    【讨论】:

      猜你喜欢
      • 2021-11-26
      • 1970-01-01
      • 2011-11-07
      • 2016-09-11
      • 2015-09-07
      • 2016-12-26
      • 1970-01-01
      • 1970-01-01
      • 2012-07-05
      相关资源
      最近更新 更多