我有一个包含字符串的列表,像这样:
[['1 0'],
['2 0'],
['3 1 2']]
我如何在Python中将其转换为邻接表,请像这样:(所有int)
{
1: 0,
2:0,
3: 1,2
}
到目前为止,我的尝试让我做到了:
newlist = []
for word in linelist:
word = word.split(",")
newlist.append(word)
print(newlist)
产生如下:
[['1 0'],
['2 0'],
['3 1 2']]
非常感谢!
您可以像这样将其转换为字典:
adj_dict = {}
for inner_list in outer_list:
values = [int(x) for x in inner_list[0].split()]
adj_dict[values[0]] = values[1:]
这取决于你想要的字典值的数据类型,但这应该会让你得到大部分的方法:
res = {}
for e in a:
res[e[0][0]] = ','.join(e[0][1::].strip().split(' '))
您可以像这样使用嵌套式推导式和列表切片:
>>> s = [['1 0'],
... ['2 0'],
... ['3 1 2']]
>>>
>>> [{_[0]: _[1:]} for _ in [list(map(int, _[0].split())) for _ in s]]
[{1: [0]}, {2: [0]}, {3: [1, 2]}]
我们也可以使用*
运算符将其缩短一点:
>>> [{_[0]: _[1:]} for _ in [[*map(int, _[0].split())] for _ in s]]
[{1: [0]}, {2: [0]}, {3: [1, 2]}]