Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: list matching [duplicate]

I have format a list of lists with parent_id, id and name like cascade style.

My input as follows:

category = [['id','name','parent_id'],[1, 'Root', 0],[10, 'Beans', 4],[2, 'Sub Root', 1],[3, 'Fruits', 2],[4, 'Veg', 2],[5, 'Apple', 3],[6, 'Onion', 4]]

And my excepted output follows as

out_category = [[1, 'Root', 0],[2, 'Sub Root', 1],[3, 'Fruits', 2],[4, 'Veg', 2],[5, 'Apple', 3],[6, 'Onion', 4],[10, 'Beans', 4]]

I tried so far

out_category = []
for item in category[1:]:
    print item[0].split(',')
    categ = item[0].split(',')
    out_category.append(filter(lambda x: x[0]==categ[2],categ))
print out_category

1 Answers

Use filter for remove non int and sorted with key for search by first item:

sorted(filter(lambda x: isinstance(x[0], int), category), key=lambda x: x[0])

If it is difficult to understand, in two lines it looks like this:

# Remove titles (first element of category)
without_first_string_list = filter(lambda x: isinstance(x[0], int), category)

# Or you can use if this list always have only one list with titles,
#                          but if not, the sorting may be incorrect
without_first_string_list = category[1:]

# Sort by first item
sorted_list = sorted(without_first_string_list, key=lambda x: x[0])
like image 60
JRazor Avatar answered Apr 21 '26 20:04

JRazor