Python添加新行以列出重复项

2024-04-19 20:36:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图添加新行到一个列表中,但似乎只有最后一行被复制到列表中,因为多次有一个新行生成。 所以我做了一个小测试脚本来演示我的问题。 我想要的是在原始列表中添加尽可能多的行,因为行中有晚上,并在原始日期中添加一天,如果有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行与递增日期的第一个记录 最后一行是两行


Tags: theinfordatea1linenewlinepd
1条回答
网友
1楼 · 发布于 2024-04-19 20:36:43

内部循环while n > 1:不断修改相同的newline对象并将其附加到bList。因此,在bList中没有7个不同的newline对象,而是有7个对同一对象的引用

你可以把这个问题解决掉

newline = x

while n > 1:之前行,并将循环的开始更改为

while n > 1:
    newline = x[:]

这将在循环的每次迭代中创建一个新的newline对象(从x复制)

如果x是一个字符串列表,这个解决方案就可以工作。但是,如果x实际上是一个列表列表,那么您可能还需要创建这些内部列表的副本

相关问题 更多 >