python中带有列表的函数的定义

2024-04-27 01:55:35 发布

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

我想写一个函数,将采取任何名单,并给我回那个“总和”的答案。现在我为“recherche”做这个,但重点是为列表中的任何类型做这个。我的代码就是这样的。你知道吗

TYPE_RECHERCHE = "recherche"

une_formation = [
    [ TYPE_DIRIGEE, 7.50 ],
    [ TYPE_PRESENTATION, 4.5 ],
    [ TYPE_DIRIGEE, 2.00 ],
    [ TYPE_CONFERENCE, 7.0 ],
    [ TYPE_ATELIER, 2.25 ],
    [ TYPE_GROUPE_DISCUSSION, 3.00 ],
    [ TYPE_RECHERCHE, 1 ],
    [ TYPE_LECTURE, 4.0 ],
    [ TYPE_RECHERCHE, 4 ],
    [ TYPE_RECHERCHE, 2.5 ],
    [ TYPE_PRESENTATION, 3.5 ],
    [ TYPE_REDACTION, 5.5 ],
    [ TYPE_LECTURE, 10.0 ]
]


temps_formation_recherche = []
a = -1 
while a < 12:
    a = a + 1
    if une_formation[a][0] == "recherche":
        temps_formation_recherche.append(une_formation[a][1])

sum(temps_formation_recherche) # this will return 7.5

Tags: 函数答案重点列表typepresentation名单总和
3条回答

或者从itertools使用groupby

from itertools import groupby

def sum_by_type(une_formation, TYPE_String):
    return [sum(i[1] for i in group) for key, group in groupby(sorted(une_formation, key = lambda i: i[0]), lambda i: i[0]) if key == TYPE_String ][0]

你可以定义你的函数,这样它就可以把你想要找到的东西作为一个参数。然后,您可以将每个找到的项的值添加到一个临时变量中—看起来您的临时列表就快到了。 例如:

def find_total(toFind):
    temps_formation_recherche = 0
    a = -1
    while a < 12:
        a += 1
        if une_formation[a][0] == toFind:
            temps_formation_recherche += une_formation[a][1]

    return temps_formation_recherche

TYPE_RECHERCHE的情况下,它将返回7.5。在TYPE_DIRIGEE的情况下,返回9.5。你知道吗


您可以使用列表理解进一步优化代码:

def find_total(toFind):
    return sum([x[1] for x in une_formation if x[0] == toFind])

print(find_total(TYPE_RECHERCHE))  # prints 7.5
print(find_total(TYPE_DIRIGEE))    # prints 9.5

这将获取原始列表,创建一个仅包含每个匹配元素的数字部分的列表,然后使用sum函数将它们全部相加。你知道吗

要准确地理解你在追求什么有点困难,但试试这个:

def mon_fonction(une_formation, TYPE_RECHERCHE):
    tot = 0
    liste = []
    for quel, val in une_formation:
        if quel == TYPE_RECHERCHE:
            tot += val
            liste.append(val)
    print "Les vals sont:", liste
    print "en tout:", tot
    return tot

相关问题 更多 >