Home > Software design >  How to print something around the values of a list?
How to print something around the values of a list?

Time:04-25

My program allows you to write in times (they get put in a list) and the highest and lowest time of the list gets excluded and it then calculates the average of the remaining times.

Then I told the program to print out the times in the list and the average, the output looks something like this:

[1.1, 2.1, 3.1, 4.1, 5.1] average:x

I want it to put parentheses around the highest and the lowest times of the average (the ones that are excluded). I'd also like it if the times were displayed without the [] around them, which would look something like this:

(1.1), 2.1, 3.1, 4.1, (5.1) average:x

I've been scanning the internet for a solution to this but I've had no success, I guess it's a very specific problem.

Can anyone tell me if it's possible to do and if so how? I'd appreciate a pretty simple explanation, if possible, but I'll gladly learn something relatively advanced if I have to. (idk if it matters but I am using python 3)

CodePudding user response:

You want to format the results, probably using f-string if you're using Python 3.6 or above:

times = [ 6, 1, 8, 3, 9 ]                           # create list of times
mean = lambda x: sum(x) / len(x)                    # define average function
times = sorted(times)                               # sort our times
first_time = times.pop(0)                           # pop first time from list
last_time = times.pop()                             # pop last time from list
times_as_string = ", ".join(str(x) for x in times)  # e.g. "3, 6, 8" 
# now build and print out the string
print(f"({first_time}) {times_as_string} ({last_time}) average: {mean(times)}")

gives:

(1) 3, 6, 8 (9) average: 5.666666666666667

Edit:

If you are on an earlier version, you can use % syntax, e.g.:

print("(%.2f) %s (%.2f) average: %.3f" % (first_time, times_as_string, last_time, mean(times)))

which will give:

(1.00) 3, 6, 8 (9.00) average: 5.667

CodePudding user response:

try using a for loop, idk the syntax that well for python, but i assume you just need to use a simple loop and it will work :)

  • Related