python - 根据列表中的某些项目对列表中的项目进行分组
问题描述
我有一个包含 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 个元素,以此类推其他列表。我环顾四周,但没有找到可以更容易做到这一点的东西。如果您知道如何解决此问题或为我指明正确的方向,我将不胜感激。
感谢您的时间和耐心!
更新:我已将列表从图片更改为可以复制的内容。并添加了预期的输出。
解决方案
您的代码过于复杂。如果您的目标是根据 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]:
推荐阅读
- linux - Festival-festvox 覆盖其他声音
- azure-functions - 从在 .NET 5 上运行的 Azure Functions 中的类访问配置
- python-3.x - 当波在 Python 中是正弦波或方波时,是否可以用 1 个参数来描述?
- pandas - MongoDB删除不包含自定义单词的文档
- c# - PowerShell Exchange 连接 来自网络服务器的访问被拒绝,但从 localhost 工作
- deno - 如何预编译 Deno 脚本?
- smalltalk - 像 UndefinedObject 这样的类在 Pharo 中表现得像单例吗
- google-data-studio - 如何在 Google Data Studio 中使用 CASE WHEN 对数字范围进行分组
- ios - 在您接受许可之前,我可以让我的 iOS 应用程序拒绝安装吗?
- java - 我怎样才能在 Kotlin 中做到这一点?