Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python组列表_Python_Python 3.x_List - Fatal编程技术网

Python组列表

Python组列表,python,python-3.x,list,Python,Python 3.x,List,我有以下格式的列表: [['Sarah', '12', 'Chocolate'], ['Anders', '11', 'Vanilla'], ['Sarah', '13', 'Strawberry'], ['John', '11', 'None'], # ... ] 我想将子列表分组如下: [['Sarah', '12', 'Chocolate', '13', 'Strawberry'], ['Anders', '11', 'Vanilla'], ['John', '11', 'N

我有以下格式的列表:

[['Sarah', '12', 'Chocolate'],
 ['Anders', '11', 'Vanilla'],
 ['Sarah', '13', 'Strawberry'],
 ['John', '11', 'None'],
 # ...
]
我想将子列表分组如下:

[['Sarah', '12', 'Chocolate', '13', 'Strawberry'],
 ['Anders', '11', 'Vanilla'],
 ['John', '11', 'None'],
 # ...
]
在这里,我按照子列表的第一项进行分组,并按照第二项进行排序(因此,12岁的撒拉人排在13岁的撒拉人之前)


如何做到这一点?

您没有显示任何代码,因此我不会给出完整的解决方案

一个好的数据结构是使用
dict
,名称作为键,元组列表作为值:

data =[['Sarah', '12', 'Chocolate'],
    ['Anders', '11', 'Vanilla'],
    ['Sarah', '13', 'Strawberry'],
    ['John', '11', 'None']]

grouped = {}

for name, x, y in data:
    grouped.setdefault(name, []).append((x,y))

print(grouped)
# {'Sarah': [('12', 'Chocolate'), ('13', 'Strawberry')], 'Anders': [('11', 'Vanilla')], 'John': [('11', 'None')]}

您只需要对值进行排序。

您没有显示任何代码,因此我不会给出完整的解决方案

一个好的数据结构是使用
dict
,名称作为键,元组列表作为值:

data =[['Sarah', '12', 'Chocolate'],
    ['Anders', '11', 'Vanilla'],
    ['Sarah', '13', 'Strawberry'],
    ['John', '11', 'None']]

grouped = {}

for name, x, y in data:
    grouped.setdefault(name, []).append((x,y))

print(grouped)
# {'Sarah': [('12', 'Chocolate'), ('13', 'Strawberry')], 'Anders': [('11', 'Vanilla')], 'John': [('11', 'None')]}

您只需要对值进行排序。

一些可能的解决方案浮现在脑海中,但这里有一个。阅读评论并自由提问:

from collections import defaultdict

l = [
        ['Sarah', '12', 'Chocolate'],
        ['Anders', '11', 'Vanilla'],
        ['Sarah', '13', 'Strawberry'],
        ['John', '11', 'None'],
]

d = defaultdict(list)

for entry in l:
    d[entry[0]].append(entry[1:])

# Here d looks something like this:
# {'Sarah': [['12', 'Chocolate'], ['13', 'Strawberry']], ...}

result = [
    # 1. Sort the list by the first element of each sublist (parsed as an int).
    # 2. Flatten the result as in https://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python/952952#952952.
    # 3. Prepend the key (name).
    [k] + [item for sublist in sorted(v, key=lambda x: int(x[0])) for item in sublist]
    for k,v in d.items()
]

print(result)

# Output: [['Sarah', '12', 'Chocolate', '13', 'Strawberry'], ['Anders', '11', 'Vanilla'], ['John', '11', 'None']]

我想到了一些可能的解决方案,但这里有一个。阅读评论并自由提问:

from collections import defaultdict

l = [
        ['Sarah', '12', 'Chocolate'],
        ['Anders', '11', 'Vanilla'],
        ['Sarah', '13', 'Strawberry'],
        ['John', '11', 'None'],
]

d = defaultdict(list)

for entry in l:
    d[entry[0]].append(entry[1:])

# Here d looks something like this:
# {'Sarah': [['12', 'Chocolate'], ['13', 'Strawberry']], ...}

result = [
    # 1. Sort the list by the first element of each sublist (parsed as an int).
    # 2. Flatten the result as in https://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python/952952#952952.
    # 3. Prepend the key (name).
    [k] + [item for sublist in sorted(v, key=lambda x: int(x[0])) for item in sublist]
    for k,v in d.items()
]

print(result)

# Output: [['Sarah', '12', 'Chocolate', '13', 'Strawberry'], ['Anders', '11', 'Vanilla'], ['John', '11', 'None']]
您可以尝试以下方法:

import itertools


list_1=[['Sarah', '12', 'Chocolate'],
       ['Anders', '11', 'Vanilla'],
       ['Sarah', '13', 'Strawberry'],
       ['John', '11', 'None']]

repeated_list=[]
unique_list=[]
for item_1,item_2 in itertools.combinations(list_1,2):
    if item_1[0]==item_2[0]:
        repeated_list.append(item_1+item_2)

    else:

        for item_3 in repeated_list:
            if item_2[0] not in item_3:
                if item_2 not in unique_list:
                    unique_list.append(item_2)

            elif item_1[0] not in item_3:
                if item_1 not in unique_list:
                    unique_list.append(item_1)


print(unique_list+repeated_list)
输出:

[['John', '11', 'None'], ['Anders', '11', 'Vanilla'], ['Sarah', '12', 'Chocolate', 'Sarah', '13', 'Strawberry']]
您可以尝试以下方法:

import itertools


list_1=[['Sarah', '12', 'Chocolate'],
       ['Anders', '11', 'Vanilla'],
       ['Sarah', '13', 'Strawberry'],
       ['John', '11', 'None']]

repeated_list=[]
unique_list=[]
for item_1,item_2 in itertools.combinations(list_1,2):
    if item_1[0]==item_2[0]:
        repeated_list.append(item_1+item_2)

    else:

        for item_3 in repeated_list:
            if item_2[0] not in item_3:
                if item_2 not in unique_list:
                    unique_list.append(item_2)

            elif item_1[0] not in item_3:
                if item_1 not in unique_list:
                    unique_list.append(item_1)


print(unique_list+repeated_list)
输出:

[['John', '11', 'None'], ['Anders', '11', 'Vanilla'], ['Sarah', '12', 'Chocolate', 'Sarah', '13', 'Strawberry']]

您尝试了什么?您可能希望保留(名称、年龄、味道)元组,并将元组放入列表中,而不是将列表连接在一起。我猜你真的想用sorted对列表进行排序你尝试了什么?你可能想保留(名称、年龄、味道)元组,并将元组放在一个列表中,而不是将列表连接在一起。我猜您实际上希望使用sortedra对列表进行排序,而不是使用
not dict.get(key)
,使用
key not in dict
。用于添加列表,而不是
if:。。。其他:…
您可以使用
dict.setdefault(key,[])。append(…)
@MartijnPieters:非常好的评论,谢谢。关于
setdefault
,您也是正确的。由于OP没有显示任何代码,我不想使用
defaultdict
groupby
dict.setdefault
来尽可能地简化示例。我不明白
setdefault
为什么不简单。如果你要回答,请使用最佳实践。为什么要让事情变得愚蠢?@MartijnPieters:Modified。关于
dict.setdefault
让我烦恼的是,它被用作一个getter,这可能会令人惊讶。在我看来,这并不比使用
defaultdict
更令人惊讶。与其使用
not dict.get(key)
,不如使用
key not in dict
。用于添加列表,而不是
if:。。。其他:…
您可以使用
dict.setdefault(key,[])。append(…)
@MartijnPieters:非常好的评论,谢谢。关于
setdefault
,您也是正确的。由于OP没有显示任何代码,我不想使用
defaultdict
groupby
dict.setdefault
来尽可能地简化示例。我不明白
setdefault
为什么不简单。如果你要回答,请使用最佳实践。为什么要让事情变得愚蠢?@MartijnPieters:Modified。关于
dict.setdefault
的问题让我感到困扰的是,它被用作getter,这可能会令人惊讶。在我看来,这并不比使用
defaultdict
更令人惊讶。