在列表列表中搜索字符串

时间:2019-07-15 09:06:41

标签: python-3.x list

我有一个包含字符串列表的列表:

cloud = [['SCT015, SCT040'], ['FEW015, SCT025'], ['FEW015, SCT045'],['FEW020, FEW040'], ['FEW010, FEW020, FEW040'], ['FEW012, FEW020, FEW040']],

,并且我想删除任何'FEW'实例以返回如下内容:

cleanCloud = [['SCT015, SCT040'], ['SCT025'], ['SCT045'], [], [], []]

我尝试了if语句,例如:

cleanCloud = []

for i in cloud:
    if i[0][:3] == 'FEW':
        cleanCloud.append(i[0][8:])
    elif i[0][:3] == 'SCT':

但是我似乎只是因为for循环而“迷失了”。也许正则表达式可能会更好,但是我在思考如何搜索和删除时会遇到麻烦。

4 个答案:

答案 0 :(得分:0)

您似乎需要带有列表理解功能的正则表达式。

import re
cloud = [['SCT015, SCT040'], ['FEW015, SCT025'], ['FEW015, SCT045'],['FEW020, FEW040'], ['FEW010 FEW020, FEW040'], ['FEW012, FEW020, FEW040']]

print( [re.findall(r"\bSCT\d{3}\b", j) for i in cloud for j in i] )

输出:

[['SCT015', 'SCT040'], ['SCT025'], ['SCT045'], [], [], []]

答案 1 :(得分:0)

您可以尝试:

cloud = [['SCT015, SCT040'], ['FEW015, SCT025'], ['FEW015, SCT045'], ['FEW020, FEW040'], ['FEW010, FEW020, FEW040'], ['FEW012, FEW020, FEW040']],

output_cloud = []
for single_element in cloud[0]:
    data = (single_element[0]).split(", ")
    output_data = []
    for sigle_data in data:
        if "FEW" not in sigle_data:
            output_data.append(sigle_data)

    output_string = ", ".join(output_data)
    print(output_string)

    output_cloud.append([output_string])

print(output_cloud)

答案 2 :(得分:0)

无需使用re的简单代码

cleanCloud = []
for inner_list in cloud:
    new_inner_list = []
    for item in inner_list:
        if 'FEW' not in item:
            new_inner_list.append(item)
    cleanCloud.append(new_inner_list)
 print(cleanCloud)

答案 3 :(得分:0)

您可以像这样做:

cloud = [['SCT015, SCT040'], ['FEW015, SCT025'], ['FEW015, SCT045'],['FEW020, FEW040'], ['FEW010, FEW020, FEW040'], ['FEW012, FEW020, FEW040']]

for i in range(len(cloud)):
    cloud[i] = [", ".join(filter(lambda x:  'FEW' not in x, cloud[i][0].split(', ')))]
    cloud[i] = cloud[i] if cloud[i] != [''] else []

print (cloud)

输出:

[['SCT015, SCT040'], ['SCT025'], ['SCT045'], [], [], []]