我试图添加新行到一个列表中,但似乎只有最后一行被复制到列表中,因为多次有一个新行生成。 所以我做了一个小测试脚本来演示我的问题。 我想要的是在原始列表中添加尽可能多的行,因为行中有晚上,并在原始日期中添加一天,如果有7个晚上,我只希望有7行具有不同日期。从那以后,我生成了一个文本文件来给我发邮件,这是一种每日报告,所以我知道在我们的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行与递增日期的第一个记录 最后一行是两行
内部循环
while n > 1:
不断修改相同的newline
对象并将其附加到bList
。因此,在bList
中没有7个不同的newline
对象,而是有7个对同一对象的引用你可以把这个问题解决掉
在
while n > 1:
之前行,并将循环的开始更改为这将在循环的每次迭代中创建一个新的
newline
对象(从x
复制)如果
x
是一个字符串列表,这个解决方案就可以工作。但是,如果x
实际上是一个列表列表,那么您可能还需要创建这些内部列表的副本相关问题 更多 >
编程相关推荐