简体   繁体   中英

Filtering a list of list in python

I have got a list of list like this

testList=[[1,'test',3],[4,'test',6],[1,6,7]]

My requirement is to create another list of list as follows

rstList=[[1,'test',3],[1,6,7]]

That is, list having element 'test' need to be appended only once to the rstList.

flag = True
for item in testList:
    if ('test' in item and flag) or ('test' not in item):
        flag = False
        rtList.append(item)
testList=[[1,'test',3],[4,'test',6],[1,6,7]]
rstList = []
for item in testList:
    matched = False
    for result_item in rstList:
        if item[1] == result_item[1]:
            matched = True
    if not matched:
        rstList.append(item)

I hope following code would work for you

def genNewList(v):
    test = False
    ret = []
    for el in v:
        if ('test' in el):
            if(test == False):
                ret.append(el)
                test = True
        else:
            ret.append(el)
    return ret

testList=[[1,'test',3],[4,'test',6],[1,6,7]]

print 'Original list', testList
print 'New list', genNewList(testList)

Here you can run the script, and/or fork and play around with it.

Assuming you only want to keep the the first sub-list with 'test' element, here's one approach:

def func(x):
    global foundTest
    if 'test' not in x: return True
    elif not foundTest: foundTest = True; return True
    return False

foundTest = False
rstList = filter(func, testList)
filter(lambda x: x if 'test' in x else None, testList)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM