[英]How to make strings into a list?
我嘗試使用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']
您的輸出是這樣的,因為您反復使用print(date_)
打印單個字符串日期。 那根本不是清單。
要創建列表,請將您的日期字符串附加到列表date_list
:
import csv
import time
date_list = [] # create list of date
with open('201701.csv') as inf: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)
date_list.append(date_) # append your date string to list
print(date_list)
您可以將其編寫為生成器。 這使您能夠遍歷文件中的日期序列,或將它們一起收集在列表中。 我簡化了您的代碼:
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)
好吧,如果您想要一個date_list
那么您應該做一個!
import csv
import time
date_list = []
with open('201701.csv') as inf: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_)
date_list.append(date_)
print(date_list)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.