我有一个字典,显示一个人的旅行,其中空白列表表示步行,列表包含内容表示他/她采取的管。我想找出他/她的第一次管道旅程,其编号为' 2,3'。
specific_path_legs={0: [],
1: [],
2: ['Jubilee'],
3: ['Jubilee'],
4: [],
5: [],
6: ['Metropolitan'],
7: ['Metropolitan'],
8: ['Metropolitan'],
9: ['Metropolitan'],
10: [],
11: [],
12: [],
13: [],
14: ['Northern'],
15: ['Northern'],
16: ['Northern'],
17: ['Northern'],
18: ['Northern'],
19: [],
20: [],
21: [],
22: ['Jubilee'],
23: ['Jubilee'],
24: ['Jubilee'],
25: [],
26: [],
27: []}
我首先排除了walk部分并获得了leg_nonempty字典。
legs_nonempty={2: ['Jubilee'],
3: ['Jubilee'],
6: ['Metropolitan'],
7: ['Metropolitan'],
8: ['Metropolitan'],
9: ['Metropolitan'],
14: ['Northern'],
15: ['Northern'],
16: ['Northern'],
17: ['Northern'],
18: ['Northern'],
22: ['Jubilee'],
23: ['Jubilee'],
24: ['Jubilee']}
然后我试了
first_leg=[]
for key,value in specific_path_legs.items():
if value==legs_nonempty.itervalues().next():
first_leg.append(key)
但它返回了
first_leg=[2,3, 22, 23, 24]
我只需要[2,3]而不是[2,3,22,23,24]。有什么想法吗?
答案 0 :(得分:0)
# Sort dictionary based on keys
import collections
specific_path_legs = collections.OrderedDict(sorted(specific_path_legs.items()))
# Store your info in another dict
path_legs_dict = {}
for key, value in specific_path_legs.items():
if value and value[0] not in path_legs_dict:
path_legs_dict[value[0]] = key
print path_legs_dict
# Output: {'Jubilee': 2, 'Northern': 14, 'Metropolitan': 6}
我正在使用collections.OrderedDict
因为python中的默认dict
对象没有被排序。
答案 1 :(得分:0)
由于键是从0开始递增的,所以直到找到非空值:
for i in range(len(specific_path_legs)):
if specific_path_legs[i]:
print(i, specific_path_legs[i])
break
哪会给你:
(2, ['Jubilee'])
如果您还想匹配特定值:
for i in range(len(specific_path_legs)):
val = specific_path_legs[i]
if val and val == "Jubilee":
print(i ,specific_path_legs[i]
break