将OrderedDict转换为在python中设置

时间:2017-11-22 14:18:43

标签: python python-2.7 list set ordereddictionary

我有一个像这样的OrderedDict:

OrderedDict([
    (1666, [
        ['2ZNV', 'EDO1', 14, '2FCN', 'CD', 119],
        ['2ZNV', 'EDO', 14, '2FCN', 'CD', 119]]), 
    (1056, [['2ZNV', 'EDO', 32, '2FCN','CD', 33]]), 
    (266, [['2ZNV', 'EDO', 14, '2FCN', 'CD', 19]]), 
    (171, [
        ['2ZNV', 'ZN', 9, '2FCN', 'DVA', 19], 
        ['2ZNV', 'ZN', 9, '2FCN', 'CD', 19], 
        ['2ZNV', 'ZN', 9, '2FCN', 'ACT', 19], 
        ['2ZNV', 'EDO', 9, '2FCN', 'CD', 19], 
        ['2ZNV', 'EDO', 9, '2FCN', 'DVA', 19]]),
    (45, [
        ['2ZNV','EDO', 9, '2X8L', 'GOL', 5], 
        ['2ZNV', 'ZN', 9, '2X8L', 'GOL', 5]]),
    (6, [['2ZNV', 'EDO', 2, '2FCN', 'CD', 3]]), 
    (1, [['2ZNV', 'EDO', 1, '2FCN', 'CD', 1]])
])

是否可以在set中添加所有值但保留顺序?

我尝试转换为list,然后从元组转换为如下设置:

for k,v in od.items():
    listset.append(v)
flat = [item for sublist in listset for item in sublist]
xx = set(tuple(x) for x in flat)
print xx

但这不是保持秩序。以上结果是:

set([
    ('2ZNV', 'ZN', 9, '2FCN', 'DVA', 19),
    ('2ZNV', 'EDO', 14, '2FCN', 'CD', 119),
    ('2ZNV', 'EDO', 9, '2X8L', 'GOL', 5),
    ('2ZNV', 'EDO', 32, '2FCN', 'CD', 33),
    ('2ZNV', 'EDO', 9, '2FCN', 'DVA', 19),
    ('2ZNV', 'ZN', 9, '2FCN', 'ACT', 19),
    ('2ZNV', 'EDO', 9, '2FCN', 'CD', 19),
    ('2ZNV', 'EDO', 1, '2FCN', 'CD', 1),
    ('2ZNV', 'EDO', 14, '2FCN', 'CD', 19),
    ('2ZNV', 'ZN', 9, '2X8L', 'GOL', 5),
    ('2ZNV', 'EDO1', 14, '2FCN', 'CD', 119),
    ('2ZNV', 'EDO', 2, '2FCN', 'CD', 3),
    ('2ZNV', 'ZN', 9,'2FCN', 'CD', 19)
])

提前谢谢。

2 个答案:

答案 0 :(得分:1)

您可以使用此配方https://code.activestate.com/recipes/576694/中的OrderedSet。只是

OrderedSet([tuple(item) for sublist in od.values() for item in sublist])

答案 1 :(得分:0)

集合是无序的,但您可以创建唯一元组的列表:

listset = []
for k, v in od.items():
    if (k, v) not in listset:
        listset.append((k, v))