3

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
0

3 Answers 3

3

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])
Sign up to request clarification or add additional context in comments.

2 Comments

In this case you don't even need the key. Sorting will do the right thing and use the first element in the list.
I was trying to show how to explicitly sort on the first key. In another situation (e.g. sort by last key) sorting will behave differently and the Asker will not understand what the problem is. But yes, you are right, the first key will be sorted and sorting without a key
0

Alternatively you could do this pretty readably in a list comprehension:

sorted([item for item in category if type(item[0])==int])

Comments

0

category looks like the output of the csv module. If that's the case, you can skip the headers when you parse it by reading and discarding the first line before you read the rest of the file.

Anyway, if you want to exclude the first list in the output and then sort according to the first element in each nested list, the simplest solution would be this:

out_category = sorted(category[1:])

If you want to sort by any list index (x[0], x[1] or x[2]), you can use sorted and pass a lambda as key:

out_category = sorted(category[1:], key=lambda x : x[0]) 

8 Comments

What am I missing?
Are there any reasons why you duplicated an answer?
@JRazor I didn't duplicate anything. Whose answer are you referring to?
@JRazor Ah, the last line of your answer is almost the same. I just saw you using filter, isinstance, etc. and thought it was unnecessary. Anyway, you're abusing the voting system if you use it to "fight off competition"; it should be used to judge content.
what? Your answer repeats my with a difference in 20 minutes. I don't understand why you're putting the questions duplicates
|