【问题标题】:have a list from loop result python有一个来自循环结果python的列表
【发布时间】:2019-09-05 16:10:35
【问题描述】:

我想从 for 循环的结果中得到一个列表

我有这个代码


dates=pd.date_range(start='2019-03-04', periods=3).strftime("%Y-%m-%d").tolist()
for i in range(0,len(dates)):
    filenames = ['file.'+dates[i]]
    filenames

结果:

['file.2019-03-04']
['file.2019-03-05']
['file.2019-03-06']

而期望的结果是:


['file.2019-03-04','file.2019-03-05','file.2019-03-06']

【问题讨论】:

  • 列表理解就是您要寻找的。​​span>
  • 使用列表 append() 方法

标签: python pandas list numpy for-loop


【解决方案1】:

列表推导是您正在寻找的:

dates = pd.date_range(start='2019-03-04', periods=3).strftime("%Y-%m-%d").tolist()
['file.'+ date for date in dates]

【讨论】:

    【解决方案2】:

    如果使用 python 3.6 或更高版本,请在列表理解中使用 f-string

    [f'file.{date}' for date in dates]
    

    [出]

    ['file.2019-03-04', 'file.2019-03-05', 'file.2019-03-06']
    

    【讨论】:

      【解决方案3】:

      您需要做的是创建一个空列表,并在每次迭代时附加新文件名。一种方法是:

      dates = pd.date_range(start='2019-03-04', periods=3).strftime("%Y-%m-%d").tolist()
      filenames = []
      for date in dates:  # just iterate through the records, no indexing needed
          filenames.append('file.' + date)
      

      更 Pythonic 的方式是通过列表推导。为了保持可读性,这将是这样的:

      dates = pd.date_range(start='2019-03-04', periods=3).strftime("%Y-%m-%d").tolist()
      filenames = ["file." + date for date in dates]
      

      【讨论】:

        【解决方案4】:

        这是你需要的吗?

        dates = pd.date_range(start="2019-03-04", periods=3).strftime("%Y-%m-%d").tolist()
        
        ["file." + dates[x] for x in range(0, len(dates))]
        

        【讨论】:

          猜你喜欢
          • 2013-01-06
          • 1970-01-01
          • 1970-01-01
          • 2020-10-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-07-03
          • 1970-01-01
          相关资源
          最近更新 更多