列表理解中的字典理解

发布于 2025-02-10 00:12:21 字数 1013 浏览 1 评论 0原文

我有一个词典列表,我正在修改值。循环有一个按预期工作的

show_mac = [{'mac': '0000.0000.0000', 'port': 'GigabitEthernet1/1', 'type': 'dynamic', 'vlan': '1'},
            {'mac': '0000.0000.0000', 'port': 'TenGigabitEthernet2/1', 'type': 'dynamic', 'vlan': '1'},
            {'mac': '0000.0000.0000', 'port': 'Port-channel1', 'type': 'dynamic', 'vlan': '1'}]

for d in show_mac:
    for k, v in d.items():
        d[k] = (
            v.replace('TenGigabitEthernet', 'Te')
            .replace('GigabitEthernet', 'Gi')
            .replace('Port-channel', 'Po')
        )

pprint(show_mac)

哪个产生了这一点:

[{'mac': '0000.0000.0000', 'port': 'Gi1/1', 'type': 'dynamic', 'vlan': '1'},
 {'mac': '0000.0000.0000', 'port': 'Te2/1', 'type': 'dynamic', 'vlan': '1'},
 {'mac': '0000.0000.0000', 'port': 'Po1', 'type': 'dynamic', 'vlan': '1'}]

我正在学习如何撰写综合,并且我正在尝试弄清楚如何在上述上使用上述来实现相同的结果?

I have a list of dictionaries, that I'm modifying values in. I have a for loop that works as expected.

show_mac = [{'mac': '0000.0000.0000', 'port': 'GigabitEthernet1/1', 'type': 'dynamic', 'vlan': '1'},
            {'mac': '0000.0000.0000', 'port': 'TenGigabitEthernet2/1', 'type': 'dynamic', 'vlan': '1'},
            {'mac': '0000.0000.0000', 'port': 'Port-channel1', 'type': 'dynamic', 'vlan': '1'}]

for d in show_mac:
    for k, v in d.items():
        d[k] = (
            v.replace('TenGigabitEthernet', 'Te')
            .replace('GigabitEthernet', 'Gi')
            .replace('Port-channel', 'Po')
        )

pprint(show_mac)

Which produces this:

[{'mac': '0000.0000.0000', 'port': 'Gi1/1', 'type': 'dynamic', 'vlan': '1'},
 {'mac': '0000.0000.0000', 'port': 'Te2/1', 'type': 'dynamic', 'vlan': '1'},
 {'mac': '0000.0000.0000', 'port': 'Po1', 'type': 'dynamic', 'vlan': '1'}]

I'm learning how to write comprehensions, and I'm trying to figure out how can I use list and dictionary comprehension on the above for loop to achieve the same results?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

以往的大感动 2025-02-17 00:12:21

很难阅读/理解,但这有效:

show_mac = [{key:value.replace('TenGigabitEthernet', 'Te').replace('GigabitEthernet', 'Gi').replace('Port-channel', 'Po') for (key, value) in line.items()}) for line in show_mac]
print(show_mac)

It is hard to read/understand, but this works:

show_mac = [{key:value.replace('TenGigabitEthernet', 'Te').replace('GigabitEthernet', 'Gi').replace('Port-channel', 'Po') for (key, value) in line.items()}) for line in show_mac]
print(show_mac)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文