我正在尝试将新行添加到列表中,但似乎只有最后一行被复制到列表中,因为生成了一行新行。 所以我做了一个小测试脚本来演示我的问题。 我想要的是在原始列表中添加尽可能多的行,因为行中有NIGHTS并且在原始日期添加一天,如果有7个晚上我想要7行只有不同的日期。从那里我生成一个文本文件给我发邮件,这是一种日常报告,所以我知道在我们的B& B当天会发生什么,并打开或关闭热水锅炉
这是我在Python中的测试脚本
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from datetime import datetime, timedelta
NIGHTS = 12 # number of nights a guest stays @ our B&B
CHECKIN = 0 # date the guest checks in
aList = []
"""
contents test agenda.dat
check in nights
V V
"2016-10-27,1,*,K4,A1,*,D4,*,PD,PF,0,*,7,TEST4,remark"
"2016-10-28,1,*,K4,A1,*,D4,*,PD,PF,0,*,1,TEST1,remark"
"2016-10-29,1,*,K4,A1,*,D4,*,PD,PF,0,*,1,TEST2,remark"
"2016-10-30,1,*,K4,A1,*,D4,*,PD,PF,0,*,2,TEST3,remark"
copy past this into agenda.dat and you have your file
"""
#
# --------- convert date --------- #
def date(cDate=None, format='%Y-%m-%d'):
if not cDate:
dDate = datetime.today().date()
else:
dDate = datetime.strptime(cDate, '%Y-%m-%d')
return dDate
#
# --------- get contents agenda -------- #
#
def read_agenda():
aBooking=[]
with open("agenda.dat", "r") as f:
next(f) # skip header line
for line in f:
line = line.strip()
aBooking.append(line.split(","))
return aBooking
aList = read_agenda()
# checking out contents of aList
######
for x in aList:
print x
print "============="
# it checks out
# thought using an empty list would solve the problem, not
bList = []
newline = [] # just declaring everything would help?
n = 0 # not
#######
for x in aList:
n = int(float(x[NIGHTS]))
newline = x
# the first agenda-data line contains '7' so n = 7
while n > 1:
cDatum = date(newline[CHECKIN]).date() + timedelta(days=1)
newline[CHECKIN] = "{:%Y-%m-%d}".format(cDatum)
newline[NIGHTS] = str(1)
# just to check if the conversion went ok, yes
print newline
# output:
# ['2016-10-28', '1', '*', 'K4', 'A1', '*', 'D4', '*', 'PD',
# 'PF', '0', '*', '1', 'TEST1', 'remark']
# and now it happens adding a line to this aray ends in
# replicating n lines with the same contents
# this should not be, a new line should contain a new date
bList.append(newline)
n -=1
################
print "==== bList ========="
for y in bList:
print y
# this prints the same line 7 times!
print "=== aList =========="
for x in aList:
print x
# and yes the original data is still intact except for the 7 this turned
# into 1 as desired
问题: 我在这做错了什么 我应该得到7行,第一条记录的递增日期 最后一行有2行。
答案 0 :(得分:0)
您的内循环while n > 1:
不断修改相同的newline
对象并将其附加到bList
。因此,您在newline
中没有获得7个不同的bList
个对象,您将获得对相同 newline
对象的7个引用。
您可以通过删除
来解决此问题newline = x
在while n > 1:
之前行,并将循环的开头更改为
while n > 1:
newline = x[:]
这将在循环的每次迭代中创建一个新的newline
对象(从x
复制)。
如果x
是字符串列表,此解决方案将起作用。但是,如果x
实际上是列表列表,那么您可能还必须创建这些内部列表的副本。