如何在Python中组合相似特征的属性

发布于 2024-12-25 11:30:22 字数 433 浏览 2 评论 0原文

我有一个包含街道和页面属性的文本文件。街道可能会出现在多个页面中,以下是我的文本文件现在的外观示例:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

泼猴你往哪里跑 2025-01-01 11:30:22

您可以使用将街道名称映射到列表的字典,如下所示:

streets = {}
for line in records:
    street, space, page = line.partition(' ')
    if street not in streets:
        streets[street] = []
    streets[street].append(page)

然后您可以浏览字典并输出结果。

You can use a dictionary mapping street names to lists, like so:

streets = {}
for line in records:
    street, space, page = line.partition(' ')
    if street not in streets:
        streets[street] = []
    streets[street].append(page)

You could then go through the dictionary and output the results.

思慕 2025-01-01 11:30:22

看一下 collections.defaultdict

import collections
streets = collections.defaultdict(list)
with open('a_street_page.txt') as f:
    for line in f:
        street_name, number = line.split()
        streets[street_name].append(number)

defaultdict 的作用是当您访问尚不存在的键时调用为其构造函数提供的工厂,并将结果分配给该键。这可以让您不必检查密钥是否已经存在。您的场景正是 defaultdict 的用途。

Take a look at collections.defaultdict:

import collections
streets = collections.defaultdict(list)
with open('a_street_page.txt') as f:
    for line in f:
        street_name, number = line.split()
        streets[street_name].append(number)

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 what defaultdict is for.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文