如何在Python中组合相似特征的属性
我有一个包含街道和页面属性的文本文件。街道可能会出现在多个页面中,以下是我的文本文件现在的外观示例:
Street Page
StreetA 3
StreetA 4
StreetA 5
StreetB 21
StreetB 22
使用 python I我正在尝试将类似的道路合并到一个记录中,并将该道路的每个相应页面合并到一个属性中。以下是我希望文本文件的外观示例:
Street Page
StreetA 3, 4, 5
StreetB 21, 22
如果有人能给我任何关于如何使用 Python 完成此任务我将非常感激
I have a text file containing Street and Page attributes. Streets may appear in more than one page, here's an example of the way my text file looks now:
Street Page
StreetA 3
StreetA 4
StreetA 5
StreetB 21
StreetB 22
Using python I'm trying to combine like roads into one record with each respective page for that road combined into a single attribute. Here's an example of the way I want my text file to look:
Street Page
StreetA 3, 4, 5
StreetB 21, 22
If anybody can give me any hints for how to accomplish this using Python I would be very appreciative
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用将街道名称映射到列表的字典,如下所示:
然后您可以浏览字典并输出结果。
You can use a dictionary mapping street names to lists, like so:
You could then go through the dictionary and output the results.
看一下
collections.defaultdict
:defaultdict 的作用是当您访问尚不存在的键时调用为其构造函数提供的工厂,并将结果分配给该键。这可以让您不必检查密钥是否已经存在。您的场景正是
defaultdict
的用途。Take a look at
collections.defaultdict
:What
defaultdict
does is call the factory given to its constructor when you're accessing a key that doesn't exist yet, and assign the result to that key. This prevents you from having to check if the key already exists. Your scenario is exactly whatdefaultdict
is for.