Python 无法为CSV文件中的列生成正确的哈希表
我有一个包含以下列的CSV文件Python 无法为CSV文件中的列生成正确的哈希表,python,python-2.7,Python,Python 2.7,我有一个包含以下列的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
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
方法:我最初创建了一个字典,并将其值转换为一个集合。我建议您尝试将第二列强制转换为float,并仅添加那些有效的浮点数。 此外,可以使用集合来避免某些材质的重复值 可以这样做我使用了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}
我建议您尝试将第二列强制转换为float,并仅添加那些有效浮点数的值。 此外,可以使用集合来避免某些材质的重复值 可以这样做我使用了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}
你用过csvReader1吗?为什么包括在这里?你不能同时运行python3.x和2.7,是吗?是的,那行不应该在那里。还有它的2.7你用过csvReader1吗?为什么包括在这里?你不能同时运行python3.x和2.7,是吗?是的,那行不应该在那里。还有它的2.7