如何查询相同的键并且只将它们输出为数字?

问题描述 投票:0回答:1

我有一个列表,我想在其中过滤某个键的编号,具体取决于另一个键是否存在。

数据:

DEV_DATA: [{'.cn': 'DEVICE200002', 'ou_host_config': '&@#4e08ef42883a50fe823303bbff23fd96'}, {'.cn': 'DEVICE200003', 'ou_host_config': '&@#4e08ef42883a50fe823303bbff245135'}, {'.cn': 'DEVICE200111', 'ou_host_config': '&@#4e08ef42883a50fe823303bbff24ab22'}, {'ou_host_config': '&@#4e08ef42883a50fe823303bbff252729', '.cn': 'DEVICE200112'}, {'ou_host_config': '&@#4e08ef42883a50fe823303bbff25a19d', '.cn': 'DEVICE200222'}, {'ou_host_config': '&@#4e08ef42883a50fe823303bbff26405b', '.cn': 'DEVICE200057', 'host_serial': 'HO-STA-2103-2A77'}, {'ou_host_config': '&@#4e08ef42883a50fe823303bbff267f56', '.cn': 'DEVICE200106', 'host_serial': 'HO-STA-2011-0A66'}, {'ou_host_config': '&@#4e08ef42883a50fe823303bbff26cbb7', '.cn': 'DEVICE200116', 'host_serial': 'HO-STA-2011-0B14'}, {'host_serial': 'HO-STA-2011-0BA3', '.cn': 'DEVICE200134', 'ou_host_config': '&@#4e08ef42883a50fe823303bbff270a6c'}, {'host_serial': 'HO-STA-2011-0BA9', '.cn': 'DEVICE200138', 'ou_host_config': '&@#4e08ef42883a50fe823303bbff27497b'}, {'ou_host_config': '&@#4e08ef42883a50fe823303bbff23a830', '.cn': 'DEVICE200001'}]

查询:

with_serial = []
for e in dev_data:
    if 'host_serial' in e.keys():
        with_serial = e['.cn']
            
        print("With_Serial: ", with_serial)


not_serial = []
for e in dev_data:
    if 'host_serial' not in e.keys():
        not_serial = e['.cn']
            
        print("Not_Serial: ", not_serial)

输出是:

With_Serial:  DEVICE200057
With_Serial:  DEVICE200106
With_Serial:  DEVICE200116
With_Serial:  DEVICE200134
With_Serial:  DEVICE200138

Not_Serial:  DEVICE200001
Not_Serial:  DEVICE200002
Not_Serial:  DEVICE200003
Not_Serial:  DEVICE200111
Not_Serial:  DEVICE200112
Not_Serial:  DEVICE200222

我想要得到的是:

With_Serial:  5

Not_Serial:  6

我尝试了各种解决方案,但无法使其发挥作用。知道如何解决这个问题吗?

python-3.x flask
1个回答
0
投票

不要使用列表,而是使用整数计数器并根据您的情况递增它:

with_serial = 0
not_serial  = 0
for d in DEV_DATA:
    if 'host_serial' in d:
        with_serial += 1
    else:
        not_serial  += 1
        
with_serial
# 5

not_serial
# 6
© www.soinside.com 2019 - 2024. All rights reserved.