![](/img/trans.png)
[英]Assigning and modifying tuples as values for Python Dictionary Keys
[英]Modifying Values to Specific Keys in Python dictionary
我在下面创建了一个字典d ,并正在寻找一个带有键('a'、'b'、'c') 的字典以具有值 'd' 和 'e'。
test = ['a','b','c','d','a','b','c','e','p','q','r','s']
test2= tuple(test)
d = {test2[i:i+3]:test2[i+3] for i in range(0,len(test2)-3,1)}
print(d)
output 是:
{('a', 'b', 'c'): 'e', ('b', 'c', 'd'): 'a', ('c', 'd', 'a'): 'b', ('d', 'a', 'b'): 'c', ('b', 'c', 'e'): 'p', ('c', 'e', 'p'): 'q', ('e', 'p', 'q'): 'r', ('p', 'q', 'r'): 's'}
预期的 output 是:
{('a', 'b', 'c'): ('d','e'), ('b', 'c', 'd'): 'a', ('c', 'd', 'a'): 'b', ('d', 'a', 'b'): 'c', ('b', 'c', 'e'): 'p', ('c', 'e', 'p'): 'q', ('e', 'p', 'q'): 'r', ('p', 'q', 'r'): 's'}
问题:查看第一条评论,密钥取其最近的值e ,所以现在我正在尝试更改代码以实现所需的 output? 谢谢。
选项1:
这使用 defaultdict (d = defaultdict(list)) 创建 d。
它在 for 循环中遍历数据。 多个值附加到列表中
from collections import defaultdict
d = defaultdict(list) # create list by default
for i in range(0,len(test2)-3):
d[test2[i:i+3]].append(test2[i+3]) # append value into dictionary entry
# which is a list
# since we used d = defaultdict(list)
选项 2:形式与选项 1 类似,但使用带有 setdefault 的普通字典将键条目设为列表
d = {}
for i in range(0,len(test2)-3):
d.setdefault(test2[i:i+3], []).append(test2[i+3])
两个选项具有相同的 Output
defaultdict(<class 'list'>,
{ ('a', 'b', 'c'): ['d', 'e'],
('b', 'c', 'd'): ['a'],
('b', 'c', 'e'): ['p'],
('c', 'd', 'a'): ['b'],
('c', 'e', 'p'): ['q'],
('d', 'a', 'b'): ['c'],
('e', 'p', 'q'): ['r'],
('p', 'q', 'r'): ['s']})
这是您也可以尝试的另一种解决方案:
from collections import defaultdict
test = ['a','b','c','d','a','b','c','e','p','q','r','s']
d = defaultdict(list)
while len(test) >= 4:
*key, value = test[:4] # key -> a, b, c value -> d
d[tuple(key)].append(value)
test = test[1:]
print(d)
# defaultdict(<class 'list'>, {('a', 'b', 'c'): ['d', 'e'], ('b', 'c', 'd'): ['a'], ('c', 'd', 'a'): ['b'], ('d', 'a', 'b'): ['c'], ('b', 'c', 'e'): ['p'], ('c', 'e', 'p'): ['q'], ('e', 'p', 'q'): ['r'], ('p', 'q', 'r'): ['s']})
基本思想是它不断缩小列表test
直到剩下少于 4 个项目,并将前三个项目(a, b, c)
分组为一个元组,然后将最后一个字符d
作为一个值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.