gpt4 book ai didi

python - 遍历多个列表以找到最佳的整体组合

转载 作者:行者123 更新时间:2023-11-28 20:55:17 24 4
gpt4 key购买 nike

我有一堆文件要遍历以找到最佳组合,并且想就如何做到这一点寻求一些建议。我必须把一起组成了一支混龄“接力”队。我们(恰好)需要每个年龄段的一个人。但是,我们有一个不能超过的最大重量。我们知道每个人大概得分多少——总得分最高者获胜。

我在文件中按他们的名字、体重和分数列出了所有窥视对象,例如 5.csv 文件包含所有 5 岁的 child (姓名、体重、分数)

JonnyM,54,20
SallyR,35,18
MeganP,33,25
...

6.csv 具有相同格式的 6 岁 child

DaveL,53,30
NancyP,40,28
...

等高达 20.csv。

我想我可以通过大量输入来做到这一点:

import csv
maxweight=5000
bestscore=0
bestcombo=[]
f5 = csv.reader(open("5.csv", "r"), delimiter=',')
f6 = csv.reader(open("6.csv", "r"), delimiter=',')
...
f20 = csv.reader(open("20.csv", "r"), delimiter=',')
for name5,weight5,score5 in 5f:
for name6,weight6,score6 in 6f:
...
...(and a lot more)
for name20,weight20,score20 in 20f:
if((weight5+weight6+...weight20)<=maxweight):
if((score5+score6+...score20)>bestscore):
bestcombo=[name5,name6,...name20]

但是,必须有更好的方法。我敢肯定这很明显,但我对 Python 还是个新手。

最佳答案

您可以使用 itertools.product。您还应该使用 contextlib.ExitStack 来关闭您的文件:

from contextlib import ExitStack
import csv
import itertools

maxweight = 5000
bestscore = 0
bestcombo = []

with ExitStack() as stack:
files = [csv.reader(stack.enter_context(open("{}.csv".format(i))), delimiter=',') for i in range(5, 21)]
for combo in itertools.product(*files):
names, weight_list, score_list = zip(*combo)
weight = sum(map(int, weight_list))
score = sum(map(int, score_list))
if weight <= maxweight and score > bestscore:
bestcombo = names
bestscore = score

这是未经测试的(因为我无权访问这些文件,而且我也懒得合成有效的虚拟数据),所以如果有错误请告诉我。此外,这种方法相当幼稚,因此计算量大。

关于python - 遍历多个列表以找到最佳的整体组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57138205/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com