基于条件将python字典值转换为元组

2024-09-20 03:43:40 发布

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

我试图从下面的dict中得到一个输出,作为下面提到的元组-

Input: b = {'a':'1','S1':'OptionA','P1':'100','S2':'', 'P2':'','S3':'OptionB','P3':'80'}

Output : [('OptionA', '100'), ('OptionB', '80')]

我已经为这个编码如下,但我想一个较短的方法,可以请任何人建议-

import re
b = {'a':'1','S1':'OptionA','P1':'100','S2':'', 'P2':'','S3':'OptionB','P3':'80'}

c =[]
for k,v in b.items():
    if k.startswith('S') and v:
        for i,j in b.items():
            if i.startswith('P') and re.search(r'\d+$', k).group() == re.search(r'\d+$', i).group():
                c.append(tuple([v,j]))

print(c)

Tags: andinreforifs3itemsp2
2条回答

也许有一张单子?你知道吗

>>> b = {'a':'1','S1':'OptionA','P1':'100','S2':'', 'P2':'','S3':'OptionB','P3':'80'}
>>> [(v, b['P'+k[1:]]) for k,v in b.items() if re.match('^S\d+$',k) and v and 'P'+k[1:] in b]
[('OptionB', '80'), ('OptionA', '100')]

只有匹配S<digits>的非空值与P<digits>成对。你知道吗


根据评论更新案例。如果需要将Stgy1Per1匹配,列表理解解决方案将开始失去魅力,变得有点不可读。如果不能简化配对条件,for循环可能是一种更干净的方法。你知道吗

>>> b = {'a':'1','Stgy1':'OptionA','Per1':'100','Stgy2':'', 'Per2':'','Stgy3':'OptionB','Per3':'80'}
>>> [(v, w) for s,v in b.items() for p,w in b.items() if s[0]=='S' and p[0]=='P' and v and w and re.search('\d+$',s).group()==re.search('\d+$',p).group()]
[('OptionB', '80'), ('OptionA', '100')]

我只想使用异常处理来忽略不符合您的模式的键:

c = []
for k, v in b.items():
    if not k.startswith('S') or not v:
        continue
    new_key = v
    try:
        n = int(k[1:])
        new_value = b['P%d' % (n,)]
    except KeyError, ValueError:
        continue
    c.append((new_key, new_value))

减少行数并不一定能改进代码。你知道吗

相关问题 更多 >