简体   繁体   English

Python:如何通过比较列表的内容将列表拆分为多个?

[英]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.如果您想更美观地使用可以使用 functools 中的过滤器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在python 3中将列表的元素拆分为多个元素? - How do I split an element of a list into multiple elements in python 3? 我想在第一次出现时用一个字符分割一个字符串,该字符属于一个字符列表。 如何在python中做到这一点? - I want to split a string by a character on its first occurence, which belongs to a list of characters. How to do this in python? 如何将bytearray的内容复制到列表(Python)? - How do I copy the contents of a bytearray to a list (Python)? 如何将以下 Python 字符串拆分为字符串列表? - How do I split up the following Python string in to a list of strings? 如何在多个文件中拆分Python Tkinter代码 - How do I split up Python Tkinter code in multiple files 如何使用独立于平台的实现在Python中复制文件夹及其内容(文件/子目录) - How do I copy a folder and its contents (files/subdirectories) in Python with platform independent implementation 将一个列表与其他两个大于/小于的列表进行比较 - python 3. 我该怎么做? - Comparing a list to two other lists with greater/less than - python 3. How do I do it? 如何在 Python 中将字符串列表拆分为多个列表 - How to split a string list into multiple lists in Python 我如何打印此列表的实际内容 - How do I print the actual contents of this list 如何将列表的内容作为字符串获取? - How do I get the contents of a list as a string?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM