[英]Create dict with key/value and key/value reversed
有這樣的清單
example = ['ab', 'cd']
我需要得到{'a': 'b', 'b': 'a', 'c': 'd', 'd': 'c'}
使用常規循環我可以這樣做:
result = {}
for i,j in example:
result[i] = j
result[j] = i
問題:如何在一條線上做同樣的事情?
另一種可能的方案
dict(example + [s[::-1] for s in example])
[s[::-1] for s in example]
創建一個包含所有字符串的新列表。 example + [s[::-1] for s in example]
將列表組合在一起。 然后dict
構造函數從鍵值對列表(每個字符串的第一個字符和最后一個字符)構建一個字典:
In [5]: dict(example + [s[::-1] for s in example])
Out[5]: {'a': 'b', 'b': 'a', 'c': 'd', 'd': 'c'}
列表理解與字典更新
[result.update({x[0]:x[1],x[1]:x[0]}) for x in example]
字典理解應該做:
In [726]: {k: v for (k, v) in map(tuple, example + map(reversed, example))} # Python 2
Out[726]: {'a': 'b', 'b': 'a', 'c': 'd', 'd': 'c'}
In [727]: {s[0]: s[1] for s in (example + [x[::-1] for x in example])} # Python 3
Out[727]: {'b': 'a', 'a': 'b', 'd': 'c', 'c': 'd'}
你可以用;
分開邏輯線
result=dict(example); result.update((k,v) for v,k in example)
但是當然
result=dict(example+map(reversed,example)) # only in python 2.x
要么
result=dict([(k,v) for k,v in example]+[(k,v) for v,k in example])
工作也是。
example = ['ab', 'cd']
res1={x[1]:x[0] for x in example}
res2={x[0]:x[1] for x in example}
res=res1.update(res2)
print res1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.