多个日期时间列表的Python交集
我试图找到5个datetime对象列表的交集列表。我知道列表的交集问题在这里出现了很多,但是我的代码并没有按照预期的那样运行(就像其他问题中的代码一样) 下面是5个列表的前3个元素,最后是列表的确切长度多个日期时间列表的Python交集,python,list,datetime,intersection,Python,List,Datetime,Intersection,我试图找到5个datetime对象列表的交集列表。我知道列表的交集问题在这里出现了很多,但是我的代码并没有按照预期的那样运行(就像其他问题中的代码一样) 下面是5个列表的前3个元素,最后是列表的确切长度 [datetime.datetime(2014, 8, 14, 19, 25, 6), datetime.datetime(2014, 8, 14, 19, 25, 7), datetime.datetime(2014, 8, 14, 19, 25, 9)] # length 38790 [da
[datetime.datetime(2014, 8, 14, 19, 25, 6), datetime.datetime(2014, 8, 14, 19, 25, 7), datetime.datetime(2014, 8, 14, 19, 25, 9)] # length 38790
[datetime.datetime(2014, 8, 14, 19, 25, 6), datetime.datetime(2014, 8, 14, 19, 25, 7), datetime.datetime(2014, 8, 14, 19, 25, 9)] # length 38818
[datetime.datetime(2014, 8, 14, 19, 25, 6), datetime.datetime(2014, 8, 14, 19, 25, 7), datetime.datetime(2014, 8, 14, 19, 25, 9)] # length 38959
[datetime.datetime(2014, 8, 14, 19, 25, 6), datetime.datetime(2014, 8, 14, 19, 25, 7), datetime.datetime(2014, 8, 14, 19, 25, 9)] # length 38802
[datetime.datetime(2014, 8, 14, 19, 25, 6), datetime.datetime(2014, 8, 14, 19, 25, 7), datetime.datetime(2014, 8, 14, 19, 25, 9)] # length 40415
我已经把这些列表列了一个名为《时代》的列表。我试过两种相交的方法
方法1:
此方法生成的列表长度20189
,运行时间为104秒
方法2:
此方法生成的列表长度20148
,运行时间为0.1秒
我在这方面遇到了两个问题。第一个问题是,这两种方法产生不同大小的交点,我不知道为什么。另一个问题是datetime对象
datetime.datetime(2014,8,14,19,25,6)
显然在所有5个列表中(见上文),但当我打印时(datetime.datetime(2014,8,14,19,25,6)会返回False)。列表可能有重复项,这会导致长度不一致。为了避免这些重复,您可以将每个日期时间列表转换为一个集合:
map(set, times)
这将为您提供一个集合列表(删除重复时间)。要查找交叉点,可以使用:
根据您的示例,交叉点将设置为以下集合:
set([datetime.datetime(2014, 8, 14, 19, 25, 9), datetime.datetime(2014, 8, 14, 19, 25, 6), datetime.datetime(2014, 8, 14, 19, 25, 7)])
您的第一个列表次[0]
有重复的元素;这就是不一致的原因。如果在第一个代码段中执行intersection=list(set(times[0]))
,问题就会消失
至于您的第二个代码,如果您从不在列表和集合之间进行更改,代码将更快:
intersection = set(times[0]) # make a set of the first list
for timeset in times[1:]:
intersection.intersection_update(timeset)
# if necessary make into a list again
intersection = list(intersection)
实际上,因为交集支持多个iterables作为单独的参数。您只需将所有代码替换为:
intersection = set(times[0]).intersection(*times[1:])
对于交叉口中的问题,实例是实际的datetime.datetime
还是假装的?至少时间戳似乎不知道时区。可能有重复的时间,您可以这样做:
蟒蛇3:
import functools
result = functools.reduce(lambda x, y: set(x) & set(y), times)
蟒蛇2:
result = reduce(lambda x, y: set(x) & set(y), times)
我想你已经回答了关于长度差异的来源的问题。在所有的输入列表中都有datetime.datetime实例,它只包含在集中一次,但在列表中有5次。第二,初始列表中的datetime对象是否知道时区?
intersection = set(times[0]).intersection(*times[1:])
import functools
result = functools.reduce(lambda x, y: set(x) & set(y), times)
result = reduce(lambda x, y: set(x) & set(y), times)
intersection = set(*times[:1]).intersection(*times[1:])