相关疑难解决方法(0)

Python:如果存在值,则通过更新而不是覆盖来进行字典合并

如果我有2个dicts如下:

d1 = {('unit1','test1'):2,('unit1','test2'):4}
d2 = {('unit1','test1'):2,('unit1','test2'):''}
Run Code Online (Sandbox Code Playgroud)

为了"合并"它们:

z = dict(d1.items() + d2.items())
z = {('unit1','test1'):2,('unit1','test2'):''}
Run Code Online (Sandbox Code Playgroud)

工作良好.另外要做什么,如果我想比较两个词典的每个值,如果d1中的值为空/无/',则只将d2更新为d1?

[编辑] 问题:当将d2更新为d1时,当存在相同的键时,我想仅保持数值(来自d1或d2)而不是空值.如果两个值都为空,那么保持空值没有问题.如果两者都有值,则应保留d1值.:)(lota if-else ..我会在此期间尝试自己)

d1 = {('unit1','test1'):2,('unit1','test2'):8,('unit1','test3'):''}
d2 = {('unit1','test1'):2,('unit1','test2'):'',('unit1','test3'):''}

#compare & update codes

z = {('unit1','test1'):2,('unit1','test2'):8, ('unit1','test2'):''} # 8 not overwritten by empty.
Run Code Online (Sandbox Code Playgroud)

请帮忙建议.

谢谢.

python merge dictionary compare

42
推荐指数
6
解决办法
5万
查看次数

Python:搜索元组列表

我有一个元组列表,例如

>>> l = [ ("a",1), ("b",2), ("c",3) ]
Run Code Online (Sandbox Code Playgroud)

我可以假设元素是独一无二的.现在我想获得该元组的第一个元素,其第二个元素是2('b'在本例中).首次尝试是:

>>> [ x for x, y in l if y == 2 ][0]
'b'
Run Code Online (Sandbox Code Playgroud)

这看起来有些麻烦,因为这会创建第二个列表,仅用于索引第0个元素.另一种方法是反转给定列表中的所有元组l并构建一个字典,然后索引该字典:

>>> dict([ (y, x) for x, y in l ])[2]
'b'
Run Code Online (Sandbox Code Playgroud)

考虑到反转列表和创建字典所涉及的数据混乱量,这似乎更加尴尬.最后,最简单但也许最快的方法是简单地迭代列表:

>>> def get(l) :
...     for x, y in l :
...         if y == 2 : 
...             return x
...     assert not "Should not happen."
... 
>>> get(l)
'b'
Run Code Online (Sandbox Code Playgroud)

我的问题是:有没有更好,更pythonic的方式来搜索这个列表?

search tuples list python-3.x

6
推荐指数
1
解决办法
5854
查看次数

Python不在字典条件语句中的表现

有人知道关于速度和资源使用什么更好的方法吗?链接到一些可信赖的来源将不胜感激。

if key not in dictionary.keys():
Run Code Online (Sandbox Code Playgroud)

要么

if not dictionary.get(key):
Run Code Online (Sandbox Code Playgroud)

python performance dictionary

1
推荐指数
1
解决办法
152
查看次数

标签 统计

dictionary ×2

python ×2

compare ×1

list ×1

merge ×1

performance ×1

python-3.x ×1

search ×1

tuples ×1