Python:对匹配元素

2024-09-28 03:19:09 发布

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

我有以下数据结构:

a = [('customerA', '1.0.0'), ('customerB', '1.0.0'), ('customerC', '1.0.1')]
b = (('customerB', '1.1.0'), ('customerC', '1.0.1'))

我希望结果是这样的:

^{pr2}$

甚至完全跳过不存在的客户:

[('customerB', '1.0.0', '1.1.0'), ('customerC', '1.0.1', '1.0.1')]

在这种情况下,zip函数没有帮助,因为b来自客户名称的MySQLCursor.fetchall()withWHERE子句,因此如果客户不存在,它将与a不匹配:

>>> [a + (b[1],) for a, b in zip(a, b)]
[('customerA', '1.0.0', '1.1.0'), ('customerB', '1.0.0', '1.0.1')]
>>> import itertools
>>> for a, b in itertools.zip_longest(a, b):
...     print(a, b)
... 
('customerA', '1.0.0') ('customerB', '1.1.0')
('customerB', '1.0.0') ('customerC', '1.0.1')
('customerC', '1.0.1') None

Tags: 函数in名称数据结构for客户情况zip
3条回答

使用collections。在

演示:

import collections
a = [('customerA', '1.0.0'), ('customerB', '1.0.0'), ('customerC', '1.0.1')]
b = (('customerB', '1.1.0'), ('customerC', '1.0.1'))

checkDict = dict(b)
d = collections.defaultdict(list)
for i in (a + list(b)):
    if i[0] in checkDict.keys():
        d[i[0]].append(i[1])
print(d)

输出:

^{pr2}$
In [11]: a = [('customerA', '1.0.0'), ('customerB', '1.0.0'), ('customerC', '1.0.1')]
    ...: b = (('customerB', '1.1.0'), ('customerC', '1.0.1'))

In [12]: ad = dict(a)

In [13]: bd = dict(b)

In [14]: [(k, ad.get(k), bd.get(k)) for k in set(ad.keys()) & set(bd.keys())]
Out[14]: [('customerC', '1.0.1', '1.0.1'), ('customerB', '1.0.0', '1.1.0')]

你试过直接做吗?在

customers_a = dict(a)
result = [(customer, customers_a[customer], version) for customer, version in b if customer in customers_a]

现在,result就是

^{pr2}$

相关问题 更多 >

    热门问题