根据元素拆分多个列表

时间:2016-06-14 23:06:32

标签: 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_list2 = []
for item in my_list:
    if item[0] == 1:
        new_list1.append(item)
    else:
        new_list2.append(item)

所以

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

但在我看来,这是非常具体而且不是很好,所以必须有更好的方法来做到这一点。

5 个答案:

答案 0 :(得分:2)

new_list1 = [item for item in my_list if item[0] == 1]

new_list2 = [item for item in my_list if item[0] != 1]

输出: -

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

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

答案 1 :(得分:1)

这应该有效:

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]

此处有一些关于此的讨论:Python: split a list based on a condition?

答案 2 :(得分:1)

您可以使用列表推导并使用以下2个参数定义函数,第一个参数是原始列表,第二个是键(例如1或2)

    def get_list(original_list, key):
        return [x for x in original_list if x[0] == key]

    print(get_list(my_list, 1))
    print(get_list(my_list, 2))

输出:

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

答案 3 :(得分:1)

一个简单的解决方案是使用字典。

from collections import defaultdict

dict_of_lists = defaultdict(list)
for item in my_list:
    dict_of_lists[item[0]].append(item[1:])

这对于你的" ids"可以是任何对象。

如果您想创建变量来存储它们,您可以根据所需的密钥获取列表。

newlist1 = dict_of_lists[1]
newlist2 = dict_of_lists[2]

答案 4 :(得分:-2)

您可能希望列出一个列表,以便索引键的条目列表位于 new_list [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']]