Python 根据元素将一个列表拆分为多个

Python 根据元素将一个列表拆分为多个,python,list,Python,List,假设您有一个列表列表,例如: my_list = [[1, "foo"], [2, "bar"], [1, "dog"], [2, "cat"], [1, "fox"], [1, "jar"], [2, "ape"], [2, "cup"], [2, "gym"], [1, "key"]] 您想根据my_list中每个列表的第一个元素创建(在本例中是两个,但可能更多)两个新的不同列表,您将如何做到这一点 当然,你可以这样做: new_list1 = [] new_list

假设您有一个列表列表,例如:

my_list = [[1, "foo"], [2, "bar"], [1, "dog"], [2, "cat"], [1, "fox"],
           [1, "jar"], [2, "ape"], [2, "cup"], [2, "gym"], [1, "key"]]
您想根据
my_list
中每个列表的第一个元素创建(在本例中是两个,但可能更多)两个新的不同列表,您将如何做到这一点

当然,你可以这样做:

new_list1 = []
new_list2 = []
for item in my_list:
    if item[0] == 1:
        new_list1.append(item)
    else:
        new_list2.append(item)
所以

但在我看来,这确实很具体,也不是很好,所以必须有更好的方法来做到这一点。

这应该是可行的:

new_list1 = [i for i in my_list if my_list[0] == 1]
new_list2 = [i for i in my_list if my_list[0] != 1]

这里有一些过去的讨论:

您可以使用列表理解并定义一个具有两个参数的函数,如下所示,第一个参数是原始列表,第二个是键(例如1或2)

输出:

[[1, 'foo'], [1, 'dog'], [1, 'fox'], [1, 'jar'], [1, 'key']]
[[2, 'bar'], [2, 'cat'], [2, 'ape'], [2, 'cup'], [2, 'gym']]

一个简单的解决办法是使用字典

from collections import defaultdict

dict_of_lists = defaultdict(list)
for item in my_list:
    dict_of_lists[item[0]].append(item[1:])
对于“id”可以是任何对象的一般情况,这很好

如果要创建变量来存储它们,可以根据所需的键获取列表

newlist1 = dict_of_lists[1]
newlist2 = dict_of_lists[2]
输出:-

[1,'foo'],[1,'dog'],[1,'fox'],[1,'jar'],[1,'key']]


[[2',bar'],[2',cat'],[2',ape'],[2',cup'],[2',gym']

您可能需要创建一个列表列表,这样带有键index的条目列表位于新列表[index]

my_list = [[1, "foo"], [2, "bar"], [1, "dog"], [2, "cat"], [1, "fox"],
           [1, "jar"], [2, "ape"], [2, "cup"], [2, "gym"], [1, "key"]]

new_list = [[x for x in my_list if x[0] == value]
                  for value in range(1 + max([key[0] for key in my_list]))]
new_list1 = new_list[1]
new_list2 = new_list[2]
print new_list1
print new_list2
输出:

[[1, 'foo'], [1, 'dog'], [1, 'fox'], [1, 'jar'], [1, 'key']]
[[2, 'bar'], [2, 'cat'], [2, 'ape'], [2, 'cup'], [2, 'gym']]

此解决方案已经发布。如果您谈论的是nbrayns的解决方案,那么他的解决方案是错误的。并且没有给出期望的输出。试着运行它@PruneThat和另一个已被删除的解决方案@nbrayns已更正帖子。您显示的输出不是OP要求的。作为替代解决方案的一部分,外部列表中有一个空列表:该位置的键值为0。
new_list1 = [item for item in my_list if item[0] == 1]

new_list2 = [item for item in my_list if item[0] != 1]
my_list = [[1, "foo"], [2, "bar"], [1, "dog"], [2, "cat"], [1, "fox"],
           [1, "jar"], [2, "ape"], [2, "cup"], [2, "gym"], [1, "key"]]

new_list = [[x for x in my_list if x[0] == value]
                  for value in range(1 + max([key[0] for key in my_list]))]
new_list1 = new_list[1]
new_list2 = new_list[2]
print new_list1
print new_list2
[[1, 'foo'], [1, 'dog'], [1, 'fox'], [1, 'jar'], [1, 'key']]
[[2, 'bar'], [2, 'cat'], [2, 'ape'], [2, 'cup'], [2, 'gym']]