代码之家  ›  专栏  ›  技术社区  ›  Arvinth Kumar

基于内容筛选字符串列表时出错-python

  •  0
  • Arvinth Kumar  · 技术社区  · 6 年前

    我有一个数组'commit',其值如下,并且有seprate数组中的country list-Self.Countries(美国、中国、德国)。

    commit = [['UNITED_STATES-Consumer1_SymPercChg'],
              ['UNITED_STATES-Housing1_StndDev'],
              ['UNITED_STATES-Auto1_SymPercChg'],
              ['CHINA-Finance1_SymPercChg'],
              ['CHINA-Transport1_StndDev'],
              ['CHINA-Housing1_SymPercChg'],
              ['GERMANY-PMI1_StndDev'],
              ['GERMANY-Manufacturing1_SymPercChg'],
              ['GERMANY-Survey1_SymPercChg']
             ]
    

    我需要帮助根据国家列表拆分数组“commmit”。我试过下面的代码,但它不起作用。它返回一个空列表:

        for country in self.countries:
            self.select_columns = [x for x in commit if country in x]
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   Madhan Varadhodiyil    6 年前

    假设您的国家有多个单词的国家名称,用空格隔开(在您的问题中),而不是 _ .

    你可以这样做:

    countries = ['UNITED STATES',
                'CHINA',
                'GERMANY'
                ]
    commit = [['UNITED_STATES-Consumer1_SymPercChg'],
          ['UNITED_STATES-Housing1_StndDev'],
          ['UNITED_STATES-Auto1_SymPercChg'],
          ['CHINA-Finance1_SymPercChg'],
          ['CHINA-Transport1_StndDev'],
          ['CHINA-Housing1_SymPercChg'],
          ['GERMANY-PMI1_StndDev'],
          ['GERMANY-Manufacturing1_SymPercChg'],
          ['GERMANY-Survey1_SymPercChg']
         ]
    for c in countries:
        c = "_".join(c.split(" "))
        print c, [x for x in commit if c in x[0]]
    

    输出:

    UNITED_STATES ['UNITED_STATES-Consumer1_SymPercChg', 'UNITED_STATES-Housing1_StndDev', 'UNITED_STATES-Auto1_SymPercChg']
    
    
    CHINA ['CHINA-Finance1_SymPercChg', 'CHINA-Transport1_StndDev', 'CHINA-Housing1_SymPercChg']
    
    GERMANY ['GERMANY-PMI1_StndDev', 'GERMANY-Manufacturing1_SymPercChg', 'GERMANY-Survey1_SymPercChg']
    
        2
  •  1
  •   dustintheglass    6 年前

    试一试 regex match .

    import re
    
    pattern = re.compile('(^[A-Z_]+)(-)(.+)')
    country_data = {}
    
    for c in commit:
        match = pattern.match(c[0])
        if match:
            if match.group(1) in countries:
                if match.group(1) in country_data.keys():
                    country_data[match.group(1)].append(match.string)
                else:
                    country_data[match.group(1)] = [match.string]
    
    print(country_data)