Python和set()操作。。。&以及^

2024-10-04 03:18:45 发布

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

我尝试使用Python2.7集进行一些JSON文档比较。 我已经清理了py文档来理解set操作

在前面的代码中,我确保JSON文档具有精确的字段匹配

# convert the JSON to two set() for later operations
currSet = set(currJSON.items())
prevSet = set(prevJSON.items())

match   = currSet & prevSet 
unmatch = currSet ^ prevSet

log.info('%d, %d, Matched: %d, UnMatched: %d' % (len(currSet), len(prevSet), len(match), len(unmatch))

我总是得到len(currSet)==len(prevSet) 期望len(currSet)==len(匹配)+len(取消匹配)

^{pr2}$

不应该:len(匹配)+len(umatch)==len(S1)

我脑子里有点不对劲。。。。在


Tags: theto代码文档pyjsonconvertlen
1条回答
网友
1楼 · 发布于 2024-10-04 03:18:45

您正在比较union和{}的sum与仅one set的长度

In [80]: S1 = set([1,1,2,3])

In [81]: S2 = set([1,2,2,4])

In [82]: match = S1 & S2

In [83]: unmatch = S1 ^ S2

In [84]: match
Out[84]: {1, 2}

In [85]: unmatch
Out[85]: {3, 4}

In [86]: length = len(match)+len(unmatch)

In [87]: length
Out[87]: 4

In [88]: len(S2)  # len of just S2 not len of union and intersection
Out[88]: 3 

相关问题 更多 >