字符串和列表的元组

时间:2012-11-28 04:21:37

标签: python list

让我们说一周的日子都在有序列表中:

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

我正在制作的函数收到days_week中随机出现的元素列表:

    random_list=['mon','mon','mon','wed','sat','fri','fri','wed']

然后它应该输出一个最高出现日的元组和一个正确顺序的每一天的出现列表,如days_week中所示。所有的星期一,然后是所有的星期二:

    output:('mon',[3,0,2,0,2,1])

我的第一个想法是建立一个键的字典,这些键是本周的名称,以及那些日子出现的值:

    days_dictionary={}
    for i in random_list:
          if i in days_dictionary:
               days_dictionary[i]+=1
          else:
               days_dictionary[i]=1

这就是我被困的地方,因为我不确定如何使用字典来形成上面的输出。

编辑:我不能导入除数学之外的任何东西

4 个答案:

答案 0 :(得分:3)

你应该可以在days_dictionary

中使用这两个表达式
>>> max(days_dictionary, key=days_dictionary.get)
'mon'
>>> [days_dictionary.get(k, 0) for k in days_week]
[3, 0, 2, 0, 2, 1]

另一种方法是使用collections.Counter

>>> import random
>>> from collections import Counter
>>> days_week = ['mon', 'tues', 'wed', 'thurs', 'fri', 'sat']
>>> random_list = [random.choice(days_week) for x in range(10)]
>>> random_list
['wed', 'mon', 'mon', 'tues', 'tues', 'mon', 'wed', 'mon', 'wed', 'sat']
>>> c = Counter(random_list)
>>> c.most_common(1)[0][0]
'mon'
>>> [c.get(k, 0) for k in days_week]
[4, 2, 3, 0, 0, 1]
>>> c.most_common(1)[0][0], [c.get(k, 0) for k in days_week]
('mon', [4, 2, 3, 0, 0, 1])

答案 1 :(得分:1)

我建议您查看itertools.groupby

>>> days_week=['mon','tues','wed','thurs','fri','sat']
>>> import random
>>> random_list = [random.choice(days_week) for _ in range(10)]
>>> print random_list
['mon', 'fri', 'sat', 'wed', 'sat', 'thurs', 'wed', 'sat', 'tues', 'tues']
>>> import itertools
>>> g = itertools.groupby(sorted(enumerate(random_list), key=lambda x: x[1]), lambda x: x[1])
>>> for day, occur in g:
    print day, list(occur)


fri [(1, 'fri')]
mon [(0, 'mon')]
sat [(2, 'sat'), (4, 'sat'), (7, 'sat')]
thurs [(5, 'thurs')]
tues [(8, 'tues'), (9, 'tues')]
wed [(3, 'wed'), (6, 'wed')]

答案 2 :(得分:0)

首先:您可以使用collections.Counter来构建词典:

from collections import Counter
random_list = ['mon','mon','mon','wed','sat','fri','fri','wed']
counts = Counter(random_list)

然后你可以像这样构建频率列表:

days_week = ['mon','tues','wed','thurs','fri','sat']
freqs = [counts[d] for d in days_week if d in counts]

最终输出:

output = counts.most_common(1)[0][0], freqs ## ('mon', [3, 2, 2, 1])

答案 3 :(得分:0)

第一步是获得最常见的一天,如下:

import operator
most_common = max(days_dictionary.iteritems(), key=operator.itemgetter(1))[0]

然后列出剩余的事件列表

occur = [days_dictionary[day] for day in days_week]

然后制作元组

(most_common, occur)