Python中的元组和CSV阅读器 [英] Tuple and CSV Reader in Python

查看:56
本文介绍了Python中的元组和CSV阅读器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试相对简单的事情.

首先,我有一个以元组为键的字典,如下所示: (0,1,1,0):索引1"

First, I have dictionary with tuples as keys as follows: (0,1,1,0): "Index 1"

我正在读取一个CSV文件,该文件具有一组对应的字段,这些字段包含这些零和一的各种组合.因此,例如,CSV中的行可能显示为0,1,1,0,而没有任何引号.我正在尝试将文件中的零和一的组合与字典的键进行匹配.为此,使用标准的CSV模块

I'm reading in a CSV file which has a corresponding set of fields with various combinations of those zeroes and ones. So for example, the row in the CSV may read 0,1,1,0 without any quoting. I'm trying to match the combination of zeroes and ones in the file to the keys of the dictionary. Using the standard CSV module for this

但是问题是零和一被读为带有单引号而不是整数的字符串.换句话说,从每一行创建的元组的结构都为('0','1','1','0'),与(0,1,1,0)不匹配

However the issue is that the zeroes and ones are being read in as strings with single quotes rather than integers. In other words, the tuple created from each row is structured as ('0','1','1','0') which does not match (0,1,1,0)

有人可以阐明如何导入CSV并删除单引号吗?元组匹配和CSV读取似乎可以正常工作-只需理顺数据格式即可.

Can anyone shed some light on how to bring the CSV in and remove the single quotes? Tuple matching and CSV reading seem to work -- just need to straighten out the data format.

谢谢!

推荐答案

当您读入CSV文件时,根据所使用的库,可以指定定界符.

when you read in the CSV file, depending on what libraries you're using, you can specify the delimiter.

通常,逗号被解释为定界符.也许您可以将分隔符指定为其他内容,例如'-',以便将一组数字作为字符串一起读取,您可以使用多种方法将其转换为元组,例如使用转换字符串中提到的.html#ast.literal_eval"rel =" nofollow> ast.literal_eval 元组

typically, the comma is interpreted as the delimiter. perhaps you can specify the delimiter to be something else, e.g. '-', so that set of digits are read together as a string, and you can convert it to a tuple using variety of methods, such as using ast.literal_eval mentioned in converting string to tuple

希望有帮助!

这篇关于Python中的元组和CSV阅读器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆