比较列表

2024-06-17 14:54:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有8个列表(1月、2月、3月、4月、5月、6月、7月、8月),每个列表都包含列表格式的名称,即

['John Smith', 'Cat Stevens', 'Andrew Alexander', 'El Gordo Baba', 'Louis le Roy']

等等

如何按顺序比较这些列表,并查看名称何时出现(即订阅)和名称何时消失(即未订阅)。在

所以,假设约翰·史密斯直到二月才出现,我想知道这个信息。假设他7月份退订了,我也想要这个信息(这比前者重要得多)。在


Tags: le名称信息列表格式johnelcat
3条回答
data = {
 'jan': ['John Smith', 'Cat Stevens', 'Andrew Alexander', 'El Gordo Baba'],
 'feb': ['Louis le Roy', 'John Smith'],
 'mar': ['Cat Stevens', 'Louis le Roy']
}

from itertools import izip

keys = 'jan feb mar'.split()
for m1,m2 in izip(keys,keys[1:]):
    a = set(data[m1])
    b = set(data[m2])
    print m1, '\n\tsubscribed:', ','.join(b-a), '\n\tquit:', ','.join(a - b )

结果:

^{pr2}$
data = {
 'jan': ['John Smith', 'Cat Stevens', 'Andrew Alexander', 'El Gordo Baba'],
 'feb': ['Louis le Roy', 'John Smith'],
 'mar': ['Cat Stevens', 'Louis le Roy']
}

subs = {}
unsubs = {}
for mon in data:
    for name in data[mon]:
        if name not in subs:
            subs[name] = mon
        else:
            unsubs[name] = mon
>>> subs
{'Andrew Alexander': 'jan', 'Louis le Roy': 'mar', 'John Smith': 'jan', 'El Gordo Baba': 'jan', 'Cat Stevens': 'jan'}
>>> unsubs
{'Louis le Roy': 'feb', 'John Smith': 'feb', 'Cat Stevens': 'mar'}

不要使用列表,而是使用^{}。在

您可以使用set difference找到jan和{}之间订阅的用户:

subs = feb - jan
unsubs = jan - feb

话虽如此,你最好还是听从丹妮斯的建议。把这些放在数据库中,添加一个joinedleft日期字段,您将拥有比仅仅几个月更细的粒度,而且您不需要存储重复的数据。在

相关问题 更多 >