【问题标题】:How do you pick out certain values from a list based on their string values in Python?如何根据 Python 中的字符串值从列表中挑选出某些值?
【发布时间】:2018-02-17 13:11:25
【问题描述】:

我有一个超链接列表,包含三种类型的链接; htmcsvpdf。我想挑出那些csv

列表包含以下形式的字符串:csv/damlbmp/20160701damlbmp_zone_csv.zip

我正在考虑在字符串上运行一个 for 循环,只返回前 3 个字符串值等于 csv 的值,但我不确定如何执行此操作。

【问题讨论】:

  • 所以您只是在寻找.csv.zip 吗?还是.csv
  • 发布可测试的输入列表和预期输出

标签: python string for-loop


【解决方案1】:

我会使用link.endswith('csv')(或link.endswith('csv.zip')),其中link 是包含该链接的字符串)

例如:

lst = ['csv/damlbmp/20160701damlbmp_zone_csv.zip',
       'pdf/damlbmp/20160701damlbmp_zone_pdf.zip',
       'html/damlbmp/20160701damlbmp_zone_html.zip',
       'csv/damlbmp/20160801damlbmp_zone_csv.zip']

csv_files = [link for link in lst if link.endswith('csv.zip')]

【讨论】:

    【解决方案2】:

    如果你的名单叫links

    [x for x in links if 'csv/' in x]
    

    【讨论】:

      【解决方案3】:

      你可以试试这个

      import re
      l=["www.h.com","abc.csv","test.pdf","another.csv"] #list of links
      
      def MatchCSV(list):
          matches=[]
          for string in list:
              m=re.findall('[^\.]*\.csv',string)
              if(len(m)>0):
                  matches.append(m)
          return matches
      
      print(MatchCSV(l))
      [['abc.csv'], ['another.csv']]
      

      (endswith 也是一个不错的选择)

      【讨论】:

        【解决方案4】:

        这是一种方式:

        lst = ['csv/damlbmp/20160701damlbmp_zone_csv.zip',
               'pdf/damlbmp/20160701damlbmp_zone_pdf.zip',
               'html/damlbmp/20160701damlbmp_zone_html.zip',
               'csv/damlbmp/20160801damlbmp_zone_csv.zip']
        
        [i for i in lst if i[:3]=='csv']
        
        # ['csv/damlbmp/20160701damlbmp_zone_csv.zip',
        #  'csv/damlbmp/20160801damlbmp_zone_csv.zip']
        

        【讨论】:

        • 这很有用,谢谢,假设我想选择文件名中包含 2016 的所有条目,我会这样做吗? [i for i in csv_files if i[12:]=='2016'] ?
        • 不,你会这样做:[i for i in csv_files if '2016' in i]
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-18
        • 2015-10-10
        • 2021-03-19
        相关资源
        最近更新 更多