简体   繁体   中英

How can I create tuple from CSV file without quotes?

I'm reading CSV file and need to make tuples but I need to get rid the quotations. CSV lines examples:

57, 47, 1.04
1288, 317, 1.106
149, 84, 1.05

I tried this

import csv
from pprint import pprint

with open('./Documents/1.csv', encoding='utf-8-sig') as file:
   reader = csv.reader(file, skipinitialspace=True)
   x = list(map(tuple, reader))

and the results are:

[('57', '47', '1.04'),
 ('1288', '317', '1.106'),
 ('149', '84', '1.05')]

and I need it to be

[(57, 47, 1.04183),
 (1288, 317, 1.106),
 (149, 84, 1.05)]

Found similar question here but can't figure out the answer yet.

This needs to add an extra processing, converting with type casting:

reader = csv.reader(file, skipinitialspace=True)
# if the file has a header
# header = next(reader)
rows = [[float(row[0]), float(row[1]), float(row[2])] for row in reader]
print rows

You can use ast.literal_eval() to convert the numbers inside the tuples to their respective types:

import csv
from ast import literal_eval
from pprint import pprint

with open('1.csv', encoding='utf-8-sig') as file:
   reader = csv.reader(file, skipinitialspace=True)
   x = [tuple(map(literal_eval, x)) for x in map(tuple, reader)]
   print(x)
   # [(57, 47, 1.04), (1288, 317, 1.106), (149, 84, 1.05)]
def num(s):
        try:
            return int(s)
        except ValueError:
            return float(s)


with open('1.csv', encoding='utf-8-sig') as file:
   reader = csv.reader(file, skipinitialspace=True)
   output = [tuple(map(num, x)) for x in map(tuple, reader)]
   print(output)

output:

[(57, 47, 1.04), (1288, 317, 1.106), (149, 84, 1.05)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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