在字典中查找值变化和索引

Find the value change and the index in a dictionary

我有一本大词典:

exp_dict={0: {'length': 38.63999999999999,

  'line_nm': [['Hammersmith & City_1'],

   ['Hammersmith & City_1'],

   ['Hammersmith & City_1'],

   ['Metropolitan_1', 'Hammersmith & City_1'],

   ['Metropolitan_1', 'Hammersmith & City_1'],

   ['Metropolitan_1', 'Hammersmith & City_1'],

   ['Metropolitan_1', 'Hammersmith & City_1'],

   ['Metropolitan_1', 'Hammersmith & City_1'],

   ['Metropolitan_1', 'Hammersmith & City_1'],

   ['Metropolitan_1', 'Hammersmith & City_1'],

   ['Metropolitan_1'],

   ['Metropolitan_1'],

   ['Metropolitan_1'],

   ['Metropolitan_1', 'Hammersmith & City_1'],

   ['Metropolitan_1', 'Hammersmith & City_1'],

   ['Hammersmith & City_1'],

   ['Hammersmith & City_1'],

   ['Central', 'Hammersmith & City_1'],

   ['Central']]},
1:{'length':100,
   'line_nm':[
            ['Bakerloo'],
            ['Bakerloo'],
            ['Central'],
            ['Central'],
            ['Central'],
            ['Northern'],
            ['Northern'],
            ['Northern']

        ]

    }}

我想找出每个 'line_nm' 部分及其索引的值变化(交集)。

例如,我想知道dict['1']

dict['1']['line_nm'][10]

line_nm 改变了

['Metropolitan_1'] 

没有交集
dict['1']['line_nm'][0]

dict['1']['line_nm'][15]

line_nm 是 ['Metropolitan_1'],它与索引 10 中的前一个 ['Metropolitan_1'] 没有交集。

我需要知道所有索引

目前我只能通过以下方式查看是否有任何变化:

for key,value in dict.items():
    if set(value['line_nm'][0]).intersection(*value['line_nm'])==set([]):
        print key,True

以下是一些想法:

  • 不要使用 dict 作为变量名,因为它已经作为内置变量存在。使用 dict_(或完全不同的名称)
  • 最好在 Python 样式中包含像“==”和“=”这样的运算符周围的空格(很好的资源:PEP-8
  • 对于您的用例,您可能会从 any() 中获益

下面的代码贪婪地遍历数据结构中的嵌套列表并输出字典 d,其中 d 的键是 dict 的键和值d 个是元组列表。根据问题中列出的参数,元组包含嵌套列表中列表值的索引,以及列表值本身。

d = {}

for k,v in dict_.items():
    d[k] = []
    ind = v['line_nm'][0]
    for i, j in enumerate(v['line_nm']):
        if not any(x in j for x in ind):            
            d[k].append((i, v['line_nm'][i]))
            ind = v['line_nm'][i]

print d

# output:
# {0: [(10, ['Metropolitan_1'])], 
#  1: [(5,  ['Metropolitan_1']), (10, ['Central', 'Hammersmith & City_1'])]}

编辑

上面的代码为 exp_dict 产生了这个输出:

# output:
# {0: [(10, ['Metropolitan_1']), 
#      (15, ['Hammersmith & City_1']), 
#      (18, ['Central'])], 
#  1: [(2,  ['Central']), 
#      (5,  ['Northern'])]}

如果你只想要相关的索引,那么使用这个代码:

d = {}

for k,v in exp_dict.items():
    d[k] = []
    ind = v['line_nm'][0]
    for i, j in enumerate(v['line_nm']):
        if not any(x in j for x in ind): 
            d[k].append(i)
            ind = v['line_nm'][i]

print d

# which outputs the following for exp_dict:
# {0: [10, 15, 18], 
#  1: [2, 5]}