[英]Tuple of string and list
假設星期幾在有序列表中:
days_week=['mon','tues','wed','thurs','fri','sat']
我正在執行的功能接收在days_week
中隨機出現的元素的days_week
:
random_list=['mon','mon','mon','wed','sat','fri','fri','wed']
然后,它應按出現的最高日期輸出一個元組,並按正確的順序輸出每一天的出現列表,如days_week
例如所有mon的第一個,然后是所有tue的:
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
那就是我被困的地方,因為我不確定如何使用字典來形成上面的輸出。
編輯:我不能導入數學以外的任何東西
您應該可以在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])
我建議看看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')]
首先:您可以使用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])
第一步是獲得最普通的一天,就像這樣:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.