相关疑难解决方法(0)

比较Python中的两个词典

我有两个词典,但为了简化,我将采用这两个:

>>> x = dict(a=1, b=2)
>>> y = dict(a=2, b=2)
Run Code Online (Sandbox Code Playgroud)

现在,我想比较每key, value对中是否x具有相同的对应值y.所以我写了这个:

>>> for x_values, y_values in zip(x.iteritems(), y.iteritems()):
        if x_values == y_values:
            print 'Ok', x_values, y_values
        else:
            print 'Not', x_values, y_values
Run Code Online (Sandbox Code Playgroud)

它是有效的,因为tuple返回然后比较相等.

我的问题:

它是否正确?有更好的方法吗?更好的不是速度,我说的是代码优雅.

更新:我忘了提到我必须检查有多少key, value对是相等的.

python comparison dictionary

222
推荐指数
16
解决办法
39万
查看次数

如何制作一组列表

我有一个这样的列表列表:

i = [[1, 2, 3], [2, 4, 5], [1, 2, 3], [2, 4, 5]]
Run Code Online (Sandbox Code Playgroud)

我想得到一个包含"唯一"列表的列表(基于它们的元素),如:

o = [[1, 2, 3], [2, 4, 5]]
Run Code Online (Sandbox Code Playgroud)

我无法使用,set()因为列表中有不可清除的元素.相反,我这样做:

o = []
for e in i:
  if e not in o:
    o.append(e)
Run Code Online (Sandbox Code Playgroud)

有更简单的方法吗?

python

32
推荐指数
3
解决办法
3万
查看次数

标签 统计

python ×2

comparison ×1

dictionary ×1