简体   繁体   中英

Python: How do I split a list into multiple by comparing its contents?

I have an list such as:

list = [[1, 3, 'orange'], [3, 5, 'apple'], [2, 3, 'orange'], [7, 9, 'pear']]

and i would like to convert it into multiple lists such as:

list1 = [[1, 3, 'orange'], [2, 3, 'orange']]
list2 = [3, 5, 'apple']
list3 = [7, 9, 'pear']

Thank you.

  1. You can iterate over list.
  2. Now check if your filter element is present inside list.
for l in list:
    if filter_element in l:
        filtered_list1.append(l)
    elif condition2:
        filtered_list2.append(l)

If you want to do this more aesthetically use can use filter from functools.

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