还有什么其他方法可以将多维列表解析为python中的集合?我可以想到的另一种方法是创建字典,然后将元素逐个放入集合中。还有其他更有效的方法吗?
graph = {i: set() for l in triplets for i in l}
{graph[c[i]].add(c[i - 1]) for c in triplets for i in range(2, 0, -1)}
#input
tri = [
['t','u','p'],
['w','h','i'],
['t','s','u'],
['a','t','s'],
['h','a','p'],
['t','i','s'],
['w','h','s']
]
#i want the output
key is chat of each element from tri, value is the all chat in front of key in each element from tri
like u:{t}, ....
{
u:{'t', 's'}
p:{'u', 'a'}
h:{'w'}
i:{'h', 't'}
s:{'t', 'i', 'h'}
t:{'a'}
a:{'h'}
}
您可以遍历列表中的每个子列表,并创建输出字典,其中键作为元素,值作为所有子列表中该元素的先前元素集。
tri = [
['t','u','p'],
['w','h','i'],
['t','s','u'],
['a','t','s'],
['h','a','p'],
['t','i','s'],
['w','h','s']
]
d = {}
for x in tri:
for y in x[1:]:
d.setdefault(y, set()).update(x[x.index(y) - 1])
print(d)
# {'u': {'s', 't'},
# 'p': {'a', 'u'},
# 'h': {'w'},
# 'i': {'h', 't'},
# 's': {'h', 'i', 't'},
# 't': {'a'},
# 'a': {'h'}}
请注意,键值的顺序可能会更改,因为我们使用的set
是无序集合。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句