首页 > 解决方案 > 根据列表中的某些项目对列表中的项目进行分组

问题描述

我有一个包含 2 个元素的列表:公司 ID 和组号。我想以这种方式根据不同列表中的组号对这些公司进行分组,以便我可以对每个单独的组进行一些回归。我的清单:

59872004    0
74202004    0
1491772004  1
1476392004  1
309452004   1
1171452004  1
150842004   2
143592004   2
76202004    2
119232004   2
80492004    2
291732004   2

我当前的代码如下:

list_of_variables = []
with open(str(csv_path) + "2004-297-100.csv", 'r') as csvFile:
    reader = csv.reader(csvFile)
    for row in reader:
        list_of_variables.append(row)
    del list_of_variables[0]

list_of_lists = []
counter = 0
counter_list = 0
one_cluster = []
variable = []
for line in list_of_variables:
    print('counter: ', counter_list)
    # for testing purposes
    if counter_list == 20:
        break
    # print("cluster: ", cluster)
    # append the first line from the list to the intermediary list
    if counter_list == 0:
        one_cluster.append(line)
    if counter_list >= 1:
        if line[1] == variable[1]:
            one_cluster.append(line)
    print("one cluster : ", one_cluster)
    variable = one_cluster[counter-1]
    # print('line : ', line[1])
    # print('variable : ', variable[1])
    counter += 1
    # if the grouped number changed put the list into the final list
    # clear the intermediary list and append the current element which was not part of the previous group
    if line[1] != variable[1]:
        list_of_lists.append(one_cluster.copy())
        # print("here", list_of_lists)
        one_cluster.clear()
        one_cluster.append(line)
        counter = 0
    # print('variable', variable)
    # print('one_cluster ', one_cluster)
    counter_list += 1


print(list_of_lists)

该代码的输出如下:

[[['59872004', '0'], ['74202004', '0']], [['1491772004', '1'], ['309452004', '1'], ['1171452004', ' 1']], [['150842004', '2'], ['76202004', '2'], ['119232004', '2'], ['80492004', '2'], ['291732004' , '2']]]

代码的预期输出:

[[['59872004', '0'], ['74202004', '0']], [['1491772004', '1'], ['1476392004', '1'], ['309452004', ' 1'], ['1171452004', '1']], [['150842004', '2'], ['143592004', '2'], ['76202004', '2'], ['119232004' , '2'], ['80492004', '2'], ['291732004', '2']]]

如果您仔细观察,第 0 组做得正确,但所有其他组都缺少公司。例如,第 1 组应该有 4 个元素,但我的代码只输出 3 个元素,以此类推其他列表。我环顾四周,但没有找到可以更容易做到这一点的东西。如果您知道如何解决此问题或为我指明正确的方向,我将不胜感激。

感谢您的时间和耐心!

更新:我已将列表从图片更改为可以复制的内容。并添加了预期的输出。

标签: pythonlistgroup-bygrouping

解决方案


您的代码过于复杂。如果您的目标是根据 csv 文件的第二列对所有这些公司进行分组,只需在读取文件后添加以下代码:

from collections import defaultdict

grouping = defaultdict(list)

for line in list_of_variables:
    grouping[line[1]].append(line[0])

现在,如果你想使用一组元素,比如说第 1 组,只需运行它:

for company in grouping[1]:

推荐阅读