![](/img/trans.png)
[英]accelerate comparing dictionary keys and values to strings in list in python
[英]Comparing Python list values to dictionary keys
我正在嘗試通過將列表項與字典鍵進行比較來創建一個新列表,如果找到匹配項,那么我將 append 字典的值與全局初始化的新列表進行比較。 我正在嘗試的代碼如下
dict_1 = {'OMSS': '10.1.1.0/24', 'A&A': '10.1.2.0/24', 'AFM': '10.1.3.0/24', 'ATM': '10.1.4.0/24'}
list_1 = ['A&A', 'A&A', 'OMSS', 'OMSS', 'A&A', 'AFM', 'A&A', 'AFM', 'A&A']
list_2 = ['OMSS ', 'OMSS ', 'A&A ', 'A&A ', 'AFM ', 'A&A ', 'AFM ', 'A&A ', 'AFM ']
list_of_list1 = []
for s1 in list_1:
#print (s2)
for key, value in dict_1.items():
#print (key)
if s1 == key:
list_of_list1.append(value)
print (list_of_list1)
list_of_list2 = []
for s2 in list_2:
#print (s2)
for key, value in dict_1.items():
#print (key)
if s2 == key:
list_of_list2.append(value)
print (list_of_list2)
當我運行這個時,我得到低於 output
['10.1.2.0/24', '10.1.2.0/24', '10.1.1.0/24', '10.1.1.0/24', '10.1.2.0/24', '10.1.3.0/24', '10.1.2.0/24', '10.1.3.0/24', '10.1.2.0/24']
{'OMSS': '10.1.1.0/24', 'A&A': '10.1.2.0/24', 'AFM': '10.1.3.0/24', 'ATM': '10.1.4.0/24'}
[]
我想弄清楚為什么“list_of_list2”是空的?
list_of_list1 = [dict_1[k] for k in list_1 if k in dict_1]
list_2
的所有項目末尾都有' '
。 實際上,它們不會等於您在dict_1
中擁有的鍵。 嘗試去除多余的空格:list_of_list2 = [dict_1[k.strip()] for k in list_2 if k.strip() in dict_1]
您需要從list_2
項中刪除前導和尾隨空間以與字典鍵匹配。 這是您的問題的示例修復:
dict_1 = {'OMSS': '10.1.1.0/24', 'A&A': '10.1.2.0/24', 'AFM': '10.1.3.0/24', 'ATM': '10.1.4.0/24'}
list_1 = ['A&A', 'A&A', 'OMSS', 'OMSS', 'A&A', 'AFM', 'A&A', 'AFM', 'A&A']
list_2 = ['OMSS ', 'OMSS ', 'A&A ', 'A&A ', 'AFM ', 'A&A ', 'AFM ', 'A&A ', 'AFM ']
list_of_list1 = []
for s1 in list_1:
#print (s2)
for key, value in dict_1.items():
#print (key)
if s1 == key:
list_of_list1.append(value)
print (list_of_list1)
list_of_list2 = []
for s2 in list_2:
#print (s2)
for key, value in dict_1.items():
#print (key)
if s2.strip() == key:
list_of_list2.append(value)
print (list_of_list2)
Output:
['10.1.2.0/24', '10.1.2.0/24', '10.1.1.0/24', '10.1.1.0/24', '10.1.2.0/24', '10.1.3.0/24', '10.1.2.0/24', '10.1.3.0/24', '10.1.2.0/24']
['10.1.1.0/24', '10.1.1.0/24', '10.1.2.0/24', '10.1.2.0/24', '10.1.3.0/24', '10.1.2.0/24', '10.1.3.0/24', '10.1.2.0/24', '10.1.3.0/24']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.