作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我尝试使用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/
我是一名优秀的程序员,十分优秀!