还有其他方法可以将多维列表解析为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'}
}
答案 0 :(得分:1)
您可以遍历列表中的每个子列表,并创建以键为元素和值作为所有子列表中该元素的先前元素集的输出字典。
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
,它是无序的集合。