Questions regarding python list. The print result in the for statement is listed

Asked 2 years ago, Updated 2 years ago, 16 views

I'll use the repeat statement and the result will be

1
1
1
1
1

(Vertical, one for each line) I'm going to convert the result into a list [1,1,1,1,1,1] How do I make it? Here's the code.

num_list = [1,2,3,4,5]
total = 0
for i,n in enumerate(num_list):
    daily = (num_list[i] - total)
    if (num_list[i]-total)>0:
        total += (num_list[i]-total)
    elif (num_list[i]-total)==0:
        total += 0
    print(daily)

I want to make a daily list format.

python

2022-09-20 22:13

1 Answers

You can create a daily_list variable and put it one by one in the list as daily_list.append instead of print.

num_list = [1,2,3,4,5]
daily_list = []
total = 0
for i,n in enumerate(num_list):
    daily = (num_list[i] - total)
    if (num_list[i]-total)>0:
        total += (num_list[i]-total)
    elif (num_list[i]-total)==0:
        total += 0
    #print(daily)
    daily_list.append(daily)

print(daily_list)

Also, the way to write enumerate is a little difficult.

for i,n in enumerate(num_list):
    daily = (n - total)

Instead of using num_lists[i], you can do this.


2022-09-20 22:13

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.