我有一个类似于上周问过的问题: "Sorting dict items by key, beyond alphanumeric sorting"
问题是正确的,但现在我的dict的键只是整数:
>>>lis_nodiz = list(nodiz.items()) #list of dict items as tuples
[(2, 316),
(3, 66),
(4, 37),
(5, 15),
(6, 10),
(7, 4),
(8, 3),
(9, 1),
(10, 2),
(11, 1),
(12, 1),
(45, 1),
(109, 1),
(16, 1),
(126, 1)]
正如您猜测的那样,我正在搜索这个有序的元组列表:
[(2, 316),
(3, 66),
(4, 37),
(5, 15),
(6, 10),
(7, 4),
(8, 3),
(9, 1),
(10, 2),
(11, 1),
(12, 1),
(16, 1),
(45, 1),
(109, 1),
(126, 1)]
我试图重用“key_func”Padraic Cunningham建议我,不幸的是这个函数似乎只能用字符串类型的dict键:
def key_func(x):
"""'a0p12' -> (0, 12)"""
return tuple(int("".join(v)) for k,v in groupby(x[0], key=str.isdigit) if k)
>>>lis_nodiz_od = sorted(nodiz.items(), key=key_func)
TypeError: expected string or buffer
如何修改功能,或者我如何以其他方式来实现我的目的? 如果有人解释“key_func”是如何工作的,并且为了使它与整数一起工作而做的正确修改,我将非常感激。通过这种方式,我希望更多地了解Python编程,而不仅仅是解决我今天的问题! 非常感谢你们!
答案 0 :(得分:2)
将@app.task(bind=True)
def myfunc():
# notifications.send_message_to_admin('sdaa','dsadasdsa')
with open('text.txt','a') as f:
f.write('sa')
或> celery -A dolava beat -l info
celery beat v3.1.23 (Cipater) is starting.
__ - ... __ - _
Configuration ->
. broker -> amqp://guest:**@localhost:5672//
. loader -> celery.loaders.app.AppLoader
. scheduler -> djcelery.schedulers.DatabaseScheduler
. logfile -> [stderr]@%INFO
. maxinterval -> now (0s)
[2016-10-26 17:46:50,135: INFO/MainProcess] beat: Starting...
[2016-10-26 17:46:50,138: INFO/MainProcess] Writing entries...
[2016-10-26 17:46:51,433: INFO/MainProcess] DatabaseScheduler: Schedule changed.
[2016-10-26 17:46:51,433: INFO/MainProcess] Writing entries...
[2016-10-26 17:46:51,812: INFO/MainProcess] Scheduler: Sending due task schedule-name (dolava_app.tasks.myfunc)
[2016-10-26 17:46:51,864: INFO/MainProcess] Writing entries...
[2016-10-26 17:46:57,138: INFO/MainProcess] Scheduler: Sending due task schedule-name (dolava_app.tasks.myfunc)
[2016-10-26 17:47:02,230: INFO/MainProcess] Scheduler: Sending due task schedule-name (dolava_app.tasks.myfunc)
称为:
sorted()
其中list.sort()
是元组列表,如上所述。
注意:此处无需指定# sorted(): Creates new list with sorted order
>>> sorted(lis_nodiz)
[(2, 316), (3, 66), (4, 37), (5, 15), (6, 10), (7, 4), (8, 3), (9, 1), (10, 2), (11, 1), (12, 1), (16, 1), (45, 1), (109, 1), (126, 1)]
# list.sort(): sort the existing list
>>> lis_nodiz.sort()
>>> lis_nodiz
[(2, 316), (3, 66), (4, 37), (5, 15), (6, 10), (7, 4), (8, 3), (9, 1), (10, 2), (11, 1), (12, 1), (16, 1), (45, 1), (109, 1), (126, 1)]
。默认情况下,在第0个索引上进行词典排序;在相同值的情况下,对第一个索引进行排序。
答案 1 :(得分:0)
无需在第一个键上使用lambda排序:这是元组的默认值。
>>> sorted(x)
[(2, 316), (3, 66), (4, 37), (5, 15), (6, 10), (7, 4), (8, 3), (9, 1), (10, 2), (11, 1), (12, 1), (16, 1), (45, 1), (109, 1), (126, 1)]
它将自动对第一个成员进行排序,如果它们相等则将按第二个成员排序等。