gpt4 book ai didi

python - 如何将字符串变成列表?

转载 作者:行者123 更新时间:2023-12-01 02:33:25 25 4
gpt4 key购买 nike

我尝试使用csv.DictReader()将其中一列数据编辑成我想要的格式,代码如下:

import csv
import time
with open('201701.csv') as inf:
reader = csv.DictReader(inf)
for row in reader:
date = row['日期']
d = date.split('/')
year = int(d[0]) + 1911
month = str(d[1])
day = str(d[2])
date_ = str(year) + "{0:2}".format(month) + "{0:2}".format(day)
print(date_)

结果是这样的:

20170103
20170104
20170105
20170106
20170109
20170110
20170111
20170112
20170113
20170116
20170117
20170118
20170119
20170120
20170123
20170124

但我想要这样的数据:

date_list = ['20170103', '20170104', '20170105', '20170106', '20170109', '20170110', '20170111', '20170112', '20170113', '20170116', '20170117', '20170118', '20170119', '20170120', '20170123', '20170124']

最佳答案

您可以将其编写为生成器。这使您能够迭代文件中的日期序列,或将它们收集在一个列表中。我简化了您的代码:

import csv
import time

def get_dates(inf):
for row in csv.DictReader(inf):
year, month, day = row['日期'].split('/')
yield '{}{:02}{:02}'.format(int(year) + 1911, int(month), int(day))

用法:

# Collect into a list
with open('201701.csv') as inf:
date_list = list(get_dates(inf))
print(date_list)

# Or iterate over the dates
with open('201701.csv') as inf:
for date in get_dates(inf):
print(date)

关于python - 如何将字符串变成列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46508859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com