简体   繁体   English

列表中的Python平均,最大,最小

[英]Python Average, Max, Min from list

so I have a list like this: 所以我有一个这样的清单:

kesto = ['3m 24s', '45s', '1h 2m 40s']

I need to find an average, min and max of these. 我需要找到这些的平均值,最小值和最大值。 I have tried: 我努力了:

max_value = max(kesto)
min_value = min(kesto)
avg_value = sum(kesto)/len(kesto)

but of course it doesn't work because these are not numbers. 但是当然不行,因为这些不是数字。 and they have "m" and "s" behind them. 他们后面有“ m”和“ s”。

EDIT: This code works fine, but it only returns the first value it gets. 编辑:此代码工作正常,但它只返回它获取的第一个值。 for example if there is a "h" and a "m" it returns only the "h" so 1h 20min and 1h 15min would be "3600" both. 例如,如果有“ h”和“ m”,则仅返回“ h”,因此1h 20min和1h 15min均为“ 3600”。

            def parse_time(s):
                    s = s.split()
                    total = 0
                    for cl in s:
                            if cl[-1] == 'd':
                                total += int(cl[:-1]) * 60 * 60 * 24
                            if cl[-1] == 'h':
                                total += int(cl[:-1]) * 60 * 60
                            if cl[-1] == 'm':
                                total += int(cl[:-1]) * 60
                            if cl[-1] == 's':
                                total += int(cl[:-1])
                            return total
            kesto2 = [parse_time(s) for s in kesto]

Create a function that converts those strings to numbers, then use this function: 创建一个将这些字符串转换为数字的函数,然后使用此函数:

def conv(x):
    (m, s) = x.replace('m', '').replace('s', '').split()
    return 60 * int(m) + int(s)

max_value = max(kesto, key=conv)
min_value = min(kesto, key=conv)
avg_value = sum(map(conv, kesto))/len(kesto)

I suggest you make a function that convert your values in seconds. 我建议您创建一个函数,以秒为单位转换您的值。
For example "3m 24s" is 204 seconds. 例如,“ 3m 24s”是204秒。
I help you with the function's signature: 我可以为您提供函数签名:

def converter(value):

After you finished your function, use 完成功能后,使用

max_value = max(kesto, key=converter)
min_value = min(kesto, key=converter)

and so on... 等等...

s=0
n = []
for l in li:
   s = (60*int(l[0]))+int(l[3:4])
   n.append(s)

n is your desired list. n是您想要的列表。

you could parse those entries with strptime and then convert to timedelta objects. 您可以使用strptime解析这些条目,然后转换为timedelta对象。 these can be added and divided by integers: 这些可以相加并除以整数:

from datetime import datetime, timedelta

NULL_TIMEDELTA = timedelta()
kesto = ['3m 24s', '45s', '1h 2m 40s']

def to_timedelta(strg):
    if 'h' in strg:
        tme = datetime.strptime(strg, '%Hh %Mm %Ss').time()
    elif 'm' in strg:
        tme = datetime.strptime(strg, '%Mm %Ss').time()
    else:
        tme = datetime.strptime(strg, '%Ss').time()
    dte = datetime.combine(datetime.min, tme)  # need a datetime object
    td = dte - datetime.min                    # to create timedelta object
    return td

timedeltas = [to_timedelta(item) for item in kesto]
max_value = max(timedeltas)
min_value = min(timedeltas)
avg_value = sum(timedeltas, NULL_TIMEDELTA)/len(timedeltas)

print(max_value)  # 1:02:40
print(min_value)  # 0:00:45
print(avg_value)  # 0:22:16.333333

note you have to initialize the sum with NULL_TIMEDELTA = timedelta() . 注意,您必须使用NULL_TIMEDELTA = timedelta()初始化sum the default is 0 - but int + timedelta is not defined. 默认值为0但未定义int + timedelta

The code below converts the time to seconds and adds them to a new list called kestoS , since they are all the same units, now you can easily sort them. 下面的代码将时间转换为秒,并将它们添加到名为kestoS的新列表中,因为它们都是相同的单位,现在您可以轻松地对其进行排序。

First the minutes are separates by using split() which separates the list when an 'm' is seen. 首先,通过使用split()分隔分钟,当看到“ m”时,将分隔列表。 I only take the first value hence [0] . 我只取第一个值,因此[0] The seconds are obtained by taking the character that occur after a space up to an 's'. 通过将空格后的字符加至“ s”来获得秒数。 At the end I total the seconds and add them to kestoS . 最后,我总计秒数并将其添加到kestoS

This solution is not limited by the number of digits the seconds or the minutes have. 此解决方案不受秒或分钟的位数限制。

kestoS =[]
for time in kesto:
    minutes = time.split('m')[0]
    seconds = time.[time.find(' ') + 1: time.find('s')]
    kestoS.append((minutes*60)+seconds)
max_value = max(kestoS)
min_value = min(kestoS)
avg_value = sum(kestoS)/len(kestoS)

hope this will help 希望这会有所帮助

import re 
kesto = ['3m 24s', '1m 5s', '2m 40s']
kseto_total = []
for k in kesto:
    # here split the two values and remove the m and s from string
    minuite,second =k.replace('m','').replace('s','').split(' ')
    # convert the string into int value
    minuite=int(minuite)
    second = int(second)
    # calculating the total value and append into the new list
    kseto_total.append(minuite*60+second)
# applying max, min and calculate average
max_value = max(kseto_total)
min_value = min(kseto_total)
avg_value = sum(kseto_total)//len(kseto_total)
print(kesto)
# printing the result into converting minute and secondd
print(max_value//60,'m',max_value%60,'s\n',
      min_value//60,'m',min_value%60,'s\n',
      avg_value//60,'m',avg_value%60,'s')

Update 更新资料

def format_string(time):
    k1 = ''
    k2 = ''
    k3 = ''
    if 'h' in time:
        k1 = time
        pass
    else:
        k1 = '0h ' + k
    if 'm' in k1:
        k2 = k1
        pass
    else:
        k2 = '0m ' + k1
    if 's' in k2:
        k3 = k2
        pass
    else:
        k3 = ' 0s' + k2
    return k3

Here you call the function for string formating. 在这里,您可以调用该函数进行字符串格式化。 and then you can oparate as comment describe. 然后您就可以按照评论的描述去做。 string formatting can be done in efficient way. 字符串格式化可以以有效的方式完成。 Here is the only a simple solution. 这是唯一简单的解决方案。

This is my solution for the first part of converting the strings to usable seconds values, think it works well 这是我将字符串转换为可用秒值的第一部分的解决方案,认为效果很好

kesto = ['3m 24s', '45s', '1h 2m 40s']

def parse_time(s):
    s = s.split()
    total = 0
    for cl in s:
        if cl[-1] == 'h':
            total += int(cl[:-1]) * 60 * 60
        elif cl[-1] == 'm':     
            total += int(cl[:-1]) * 60
        elif cl[-1] == 's':
            total += int(cl[:-1])
    return total

kesto2 = [parse_time(s) for s in kesto] 

Results in kesto2 = [204, 45, 3760] which are the times in seconds. 结果kesto2 = [204,45,3760],以秒为单位的时间。 From there you can find your statistics pretty easily. 从那里您可以轻松找到统计信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM