从python中选择dict_keys的所需元素时问题

发布于 2025-01-25 00:59:54 字数 406 浏览 2 评论 0原文

我有一个字典键['a_report1','a_report2',...,'a_report10','b_report1','b_report2',...,'b_report10',]。我想从此dict_keys提取所有“ report1”。换句话说,我只能获得'a_report1''b_report1'

这是我尝试过的代码:

[report for report in list(dictionary.keys()) if 'report1' in report]

问题:它将返回'a_report10''b_report10',我也只想report1。无论如何要解决这个问题?

I have a list of dictionary keys ['A_report1', 'A_report2', ..., 'A_report10','B_report1', 'B_report2', ..., 'B_report10',]. I want to extract all 'report1' from this dict_keys. In other words, I should only get 'A_report1' and 'B_report1'.

Here's the code I tried:

[report for report in list(dictionary.keys()) if 'report1' in report]

Issue: It'll return 'A_report10' and 'B_report10' as well, I only want report1's. Anyway to fix this?

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

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

发布评论

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

评论(2

莳間冲淡了誓言ζ 2025-02-01 00:59:54

使用正则表达式如何?

import re
rx = re.compile(r'report1\b')
items = [report for report in df if rx.search(report)]

How about using a regular expression?

import re
rx = re.compile(r'report1\b')
items = [report for report in df if rx.search(report)]
怎会甘心 2025-02-01 00:59:54

这是一个简单但不舒适的解决方案,基于以下假设:您的所有报告名称都遵循格式

x = ['A_report10', 'B_report1', 'B_report2', 'B_report10']

report_1s = []

for i in x:
    if i[-7:]=='report1':
        report_1s.append(i)
        print(i)

here is a simple but non-robust solution based on the assumption that all your report names follow the format .*report<any int number>:

x = ['A_report10', 'B_report1', 'B_report2', 'B_report10']

report_1s = []

for i in x:
    if i[-7:]=='report1':
        report_1s.append(i)
        print(i)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文