根据elemen将一个列表拆分为多个

2024-04-25 12:46:43 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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"]]

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


Tags: 列表newfoomybaritemlistcat
3条回答

一个简单的解决办法是使用字典。你知道吗

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]

您可以使用列表理解来定义一个具有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']]
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,'酒吧'],[2,'猫'],[2,'猿'],[2,'杯'],[2,'健身房']]

相关问题 更多 >