0

因此,给定一个随机的一周中人们偏好列表的列表,使得在每个子列表中的 7 个位置中,第一个位置值 6 分,第二个 5 分,第三个 4 分,第四个 4 分,第三个 2 分,第二个1,最后一个没有得到任何偏好点:

    days_week=['mon','tues','wed','thurs','fri','sat','sun']

    random_day_list=[['sat','sun','wed','thurs','mon','tues','fri'],['mon','fri','sat','sun','wed','thurs','tues'],['tues','fri','sun','sat','wed','thurs','mon']]

我正在制作的函数应该输出最高得分日的元组,以及按 days_week 顺序排列的每一天的总分列表。上面的输出将是:

    ('sat',[8,7,8,5,10,14])

星期六有 14 分,所以在这种情况下,这是最喜欢的一天。

到目前为止,我想到了:

   day_dictionary={'mon':0,'tues':0,'wed':0,'thurs':0,'fri':0,'sat':0,'sun':0}
   for i in random_day_list:
         # getting into the sublist
         for j in i:
              if j in day_dictionary:
                 # stuck here:  whatever position j is in (0,1,2,3,4,5,6) if its 
                   0 add 6, 1 add 5, and so on, to day_dictionary[j]

我不能导入任何东西,除了数学女巫我怀疑我需要

4

1 回答 1

0

您需要一些方法来跟踪您所处的位置。enumerate函数为您做到了!

试试这个:

day_dictionary={'mon':0,'tues':0,'wed':0,'thurs':0,'fri':0,'sat':0,'sun':0}
for i in random_day_list:
     for position, day in enumerate(i):
         if day in day_dictionary:
             day_dictionary[day] += (6 - position)

(As a note for the future, it would probably be better to use a defaultdict rather than manually initializing everything to 0. But since you can't import anything, your way will work fine.)

于 2012-11-28T17:04:46.187 回答