简体   繁体   English

读取csv文件有困难

[英]Difficulty with reading csv file

Write a function named "csv_to_kvs" that takes a string as a parameter representing the name of a CSV file with 4 columns in the format "string, float, float, float" and returns a new key-value store mapping strings to floating point numbers. 编写一个名为“ csv_to_kvs”的函数,该函数将字符串作为参数来表示具有4列的CSV文件名,格式为“ string,float,float,float”,并返回一个新的键-值存储,将字符串映射到浮点数。 The returned key-value store will have one pair for each row in the file with keys from the first column of the CSV file and values from the third column. 返回的键值存储将为文件中的每一行提供一对,其中CSV文件的第一列中的键来自第三列中的值。 (My code below) (下面的代码)

import csv
def csv_to_kvs(string):
  with open(string) as f:
    my_file = csv.reader(f)
    my_dict = {}
    for row in my_file:
      my_dict[row[0]] = row[2]
    return my_dict

How can I convert the values in the dictionary into floats? 如何将字典中的值转换为浮点数?

Use casting. 使用铸造。

There may be times when you want to specify a type on to a variable. 有时您可能想在变量上指定类型。 This can be done with casting. 这可以通过铸造来完成。 Python is an object-orientated language, and as such it uses classes to define data types, including its primitive types. Python是一种面向对象的语言,因此它使用类来定义数据类型,包括其原始类型。

Casting in python is therefore done using constructor functions: 因此,使用构造函数完成python中的转换:

int() - constructs an integer number from an integer literal, a float literal (by rounding down to the previous whole number), or a string literal (providing the string represents a whole number) int()-从整数文字,浮点文字(通过四舍五入为前一个整数)或字符串文字(假设字符串代表整数)构造一个整数

float() - constructs a float number from an integer literal, a float literal or a string literal (providing the string represents a float or an integer) float()-从整数文字,浮点文字或字符串文字构造一个浮点数(假设字符串表示浮点数或整数)

str() - constructs a string from a wide variety of data types, including strings, integer literals and float literals str()-根据各种数据类型构造字符串,包括字符串,整数文字和浮点文字

Reference: https://www.w3schools.com/python/python_casting.asp 参考: https : //www.w3schools.com/python/python_casting.asp

What your code should look like: 您的代码应如下所示:

import csv
def csv_to_kvs(string):
  with open(string) as f:
    my_file = csv.reader(f)
    my_dict = {}
    for row in my_file:
      my_dict[row[0]] = float(row[2])
    return my_dict

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM