将csv文件中的列(字符串)转换为int的元组

ykejflvf  于 2023-02-27  发布在  其他
关注(0)|答案(2)|浏览(367)

目前,我使用csv模块处理文件,该模块创建字典列表。

import csv
file = open('csvfile.csv')
lines = csv.reader(file)
header = next(lines)  # ['name', 'price', 'date']
# when I do the following
for line in lines:
    print(line)
# I get the following     
['xxxx', '5.00', '2/23/2023']

# assigning types to the columns to do type conversion using a function
types = [
    str,
    float,
    str  # this need to be a tuple
    # tried tuple(map(int, cannotchoosecolumn.split('/')))
    # did not work
]

# now to create a list of dicts
alist_of_dicts = [
    {
        name: func(val)
        for name, func, val in zip(header, types, line)
    }
    for line in lines
]

如何选择第三列str(2/23/2023)以使用当前使用的格式更改为tuple(2, 21, 2007)

7gs2gvoe

7gs2gvoe1#

您可以向types列表传递一个函数:

import datetime

def read_date(s):
    d = datetime.datetime.strptime(s, "%m/%d/%Y")
    return (d.month, d.day, d.year)

header = ["name", "price", "date"]
lines = [["xxxx", "5.00", "2/23/2023"]]
types = [
    str,
    float,
    read_date,
]

alist_of_dicts = [
    {name: func(val) for name, func, val in zip(header, types, line)} for line in lines
]

print(alist_of_dicts)
# prints: [{'name': 'xxxx', 'price': 5.0, 'date': (2, 23, 2023)}]

但是这段代码很难理解,我建议您使用csv.DictReader来读取csv,将其作为字符串字典-〉字符串,然后转换列

zmeyuzjn

zmeyuzjn2#

使用csv.DictReader并在读取列时对其进行转换:

import csv

with open('csvfile.csv', newline='') as file:
    a_list_of_dicts = []
    for line in csv.DictReader(file):
        line['price'] = float(line['price'])
        line['date'] = tuple(int(n) for n in line['date'].split('/'))
        a_list_of_dicts.append(line)

print(a_list_of_dicts)

csvfile.csv

name,price,date
xxxx,5.00,2/23/2023
yyyy,6.75,2/24/2023

输出:

[{'name': 'xxxx', 'price': 5.0, 'date': (2, 23, 2023)}, {'name': 'yyyy', 'price': 6.75, 'date': (2, 24, 2023)}]

相关问题