Python可变输入量

2024-06-15 01:53:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发一个程序,它可以确定一个图是否是强连通的。你知道吗

我在读一系列行的标准输入。你知道吗

这些行有两个或三个空格分隔的标记、源顶点和目标顶点的名称以及可选的十进制边权重。你知道吗

输入可能如下所示:

'''
Houston Washington        1000
Vancouver Houston 300
Dallas Sacramento          800
Miami           Ames 2000
SanFrancisco LosAngeles
ORD PVD 1000
'''

如何读入此输入并将其添加到图表中? 我相信我会使用这样的收藏:

flights = collections.defaultdict(dict)

谢谢你的帮助!你知道吗


Tags: 标记程序名称目标标准ames权重空格
1条回答
网友
1楼 · 发布于 2024-06-15 01:53:45

使用d作为数据,您可以使用split-your-line和'\n',然后去掉尾部的空白,并找到. With that you can slice your string to get the name and the number associated with it.

Here I've stored the data to a dictionary. You can modify it according to your requirement!

Use regular expression modules re.sub的最后一个匹配项来删除多余的空格。你知道吗

>>> import re
>>> d
'\nHouston Washington        1000\nVancouver Houston 300\nDallas Sacramento          800\nMiami           Ames 2000\nSanFrancisco LosAngeles\nORD PVD 1000\n'
>>>[{'Name':re.sub(r' +',' ',each[:each.strip().rfind(' ')]).strip(),'Flight Number':each[each.strip().rfind(' '):].strip()} for each in filter(None,d.split('\n'))]
[{'Flight Number': '1000', 'Name': 'Houston Washington'}, {'Flight Number': '300', 'Name': 'Vancouver Houston'}, {'Flight Number': '800', 'Name': 'Dallas Sacramento'}, {'Flight Number': '2000', 'Name': 'Miami Ames'}, {'Flight Number': 'LosAngeles', 'Name': 'SanFrancisco'}, {'Flight Number': '1000', 'Name': 'ORD PVD'}]

编辑:

为了配合你的航班

>>> flights={'Houston':{'Washington':''},'Vancouver':{'Houston':''}} #sample dict
>>> for each in filter(None,d.split('\n')):
...     flights[each.split()[0]][each.split()[1]]=each.split()[2]

相关问题 更多 >