create the list without reset the list

时间:2016-02-12 19:25:20

标签: python python-2.7

I need some help with my code. I'm creating the list to store the values in the list without reset the list.

When I try this:

for channel in channels:
    program_remaining = list()

    if current_time == start_time:
       print "the program has started"

    elif start_time != current_time < stop_time:
        print "program is half way"
        current_time = datetime.timedelta(hours = get_24_hours, minutes = get_24_minutes)
        end_program = datetime.timedelta(hours = int(program_hours), minutes = int(program_minutes))
        current_program = end_program - current_time
        test = int(current_program.seconds / 60)
    program_remaining.append(test)
    print "program_remaining"
    print program_remaining

I will get the output like this:

19:17:30 T:1872  NOTICE: [13]
19:17:30 T:1872  NOTICE: [43]
19:17:30 T:1872  NOTICE: [13]
19:17:30 T:1872  NOTICE: [43]
19:17:30 T:1872  NOTICE: [13]
19:17:30 T:1872  NOTICE: [13]
19:17:30 T:1872  NOTICE: [43]

It should be look like this:

[13]
[13, 43]
[13, 43, 13]
[13, 43, 13, 43]
[13, 43, 13, 43, 13]
[13, 43, 13, 43, 13, 13]
[13, 43, 13, 43, 13, 43]

It will keep reset the list everytime when I added the values in the list and it will keep wipe out what it was previously added.

Can you show me how I can store the values in the list without reset the list under the for channel loop?

2 个答案:

答案 0 :(得分:1)

You need to create the list outside the for

Change:

for channel in channels:
    program_remaining = list()
    ...

with:

program_remaining = list()
for channel in channels:
    ...

答案 1 :(得分:0)

Just create the list outside the loop

program_remaining = list()
for channel in channels:
    if current_time == start_time:
       print "the program has started"

    elif start_time != current_time < stop_time:
        print "program is half way"
        current_time = datetime.timedelta(hours = get_24_hours, minutes = get_24_minutes)
        end_program = datetime.timedelta(hours = int(program_hours), minutes = int(program_minutes))
        current_program = end_program - current_time
        test = int(current_program.seconds / 60)
    program_remaining.append(test)
    print "program_remaining"
    print program_remaining

That way the list will not get initialized to an empty list at every iteration of the loop.