【问题标题】:How to generate a list of strings in which another string appears如何生成出现另一个字符串的字符串列表
【发布时间】:2021-02-23 11:07:46
【问题描述】:

我需要检查一个字符串是否存在于更大的字符串集中,如果它确实存在,则将包含它的字符串添加到另一个列表中。我有检查存在的代码,它可以正常工作,但由于我的实现,它无法添加字符串。

代码

test_list = ['temp', 'temperature']

b = ['sunny', 'cloudy', 'stempy', 'temp','newtemperature']

hits = []
hit_name = []
for test_string in b:
    res = any(item in test_string for item in test_list)
    if res == True:
        hit_name.append(item)
    hits.append(res)


# print result 
print('\n'*2, hits)

期望的输出

hit_name = ['stempy', 'temp','newtemperature']

【问题讨论】:

    标签: python list substring any


    【解决方案1】:

    你可以这样做

     hits = [x for x in b if any(s in x for s in test_list)]
    

    【讨论】:

      【解决方案2】:

      这是我应该做的代码,如果列表很大,则使用多进程。

      import joblib
      from joblib import Parallel,delayed
      test_list = ['temp', 'temperature']
      
      b = ['sunny', 'cloudy', 'stempy', 'temp','newtemperature']
      
      hit_name = []
      
      # Using un function to paralleliza it if database is big
      def func(x,y):
          if all(c in b[y] for c in test_list[x]):
              return(b[y])
      
      # using the max of processors
      number_of_cpu = joblib.cpu_count()
      # Prpeparing a delayed function to be parallelized
      delayed_funcs = (delayed(func)(x,y) for x in range(len(test_list)) for y in range(len(b)))
      # fiting it with processes and not threads
      parallel_pool = Parallel(n_jobs=number_of_cpu,prefer="processes")
      # Fillig the hit_name List
      hit_name.append(parallel_pool(delayed_funcs))
      # Droping the None
      hit_name = list(set(filter(None, hit_name[0])))
      hit_name
      

      【讨论】:

        【解决方案3】:

        有关简短而简单的解决方案,请参阅@jussi-nurminen 使用列表推导式的方法。

        如果你想坚持你原来的方法,它非常接近!您只需要附加test_string(这是正在检查的b 中的当前元素)而不是item

        test_list = ['temp', 'temperature']
        
        b = ['sunny', 'cloudy', 'stempy', 'temp','newtemperature']
        
        hits = []
        
        for test_string in b:
            if any(item in test_string for item in test_list):
                hits.append(test_string)
        
        print(hits)
        

        这给出了预期的输出:

        ['stempy', 'temp', 'newtemperature']
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-07-27
          相关资源
          最近更新 更多