无法为CSV fi中的列生成正确的哈希表

2024-06-26 16:58:48 发布

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

我有一个CSV文件,包含以下列

ZoneMaterialName1,ZoneThickness1
Copper,2.5
Copper,2.5
Aluminium,3
Zinc, 
Zinc,
Zinc,6
Aluminium,4

可以看到,有些值重复多次,有时可能为空或一个句点

我想要一个只有唯一值的哈希表,比如

ZoneMaterialName1,ZoneThickness1
Copper:[2.5]
Aluminium:[3,4]
Zinc:[6]

下面是我编写的代码,输出缺少浮点数,比如2.5,还允许空格和句点

import csv
from collections import defaultdict
import csv
afile = open('/mnt/c/python_test/Book2.csv', 'r+')
csvReader1 = csv.reader(afile)

reader = csv.DictReader(open('/mnt/c/python_test/Book2.csv'))
nodes = defaultdict(type(''))

for row in reader:

       if (row['ZoneThickness1'] !=' ' and row['ZoneThickness1'] !='.'):
               nodes[row['ZoneMaterialName1']]+=(row['ZoneThickness1'])
new_dict = {a:list(set(b)) for a, b in nodes.items()}
print new_dict

方法:我最初创建了一个字典,并将其值转换为一个集合


Tags: csvimportopenreaderrownodesmnt句点
1条回答
网友
1楼 · 发布于 2024-06-26 16:58:48

我建议您尝试将第二列强制转换为float,只添加那些有效浮点数的值。 此外,还可以使用set来避免某些材质的值重复

可以这样做(我使用Python 3.x,因为您为两个python版本都标记了这个问题):

import collections
import csv

result = collections.defaultdict(set)

with open('test.txt', 'r') as f:
    csv_r = csv.DictReader(f)

    for row in csv_r:
        try:
            v = float(row['ZoneThickness1'])
        except ValueError:
            # skip this line, because it is not a valid float
            continue

        # this will add the material if it doesn't exist yet and
        # will also add the value if it doesn't exist yet for this material
        result[row['ZoneMaterialName1']].add(v)

for k, v in result.items():
    print(k, v)

这将产生以下输出:

Copper {2.5}
Aluminium {3.0, 4.0}
Zinc {6.0}

相关问题 更多 >