有一个值列表:
list_inside = ["de:14612:1","de:14612:21","de:14612:17","de:14612:16"]
为什么我得到这个{'from': '1', 'to': '16'}
而不是{'from': '16', 'to': '16'}
。我的代码在做什么错了?
keys = ["from", "to"]
list_inside = ["de:14612:1","de:14612:21","de:14612:17","de:14612:16"]
for i in list_inside[::len(list_inside)-1]:
result = dict((key, i.join(i.split(":", 2)[2::1])) for key in keys)
print(result)
答案 0 :(得分:1)
使用
(C|M)?
输出:
[CM]?
您当前的方法是覆盖keys = ["from", "to"]
list_inside = ["de:14612:1","de:14612:21","de:14612:17","de:14612:16"]
result = {} #Declare empty dict
for key, v in zip(keys, list_inside[::len(list_inside)-1]):
result.update({key: v.split(":", 2)[-1])}) #Use dict.update to update the required values.
print(result)
变量。
答案 1 :(得分:1)
您在一个循环中多次result =
。
很明显,这里只有最后一次迭代才有效。
答案 2 :(得分:1)
此代码将获得预期的结果。
-1
编写了简单的代码。
keys = ["from", "to"]
list_inside = ["de:14612:1","de:14612:21","de:14612:17","de:14612:16"]
result = {}
result[keys[0]] = list_inside[0].split(':')[2]
result[keys[1]] = list_inside[-1].split(':')[2]
print (result)