我试图从下面的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)
也许有一张单子?你知道吗
只有匹配
S<digits>
的非空值与P<digits>
成对。你知道吗根据评论更新案例。如果需要将
Stgy1
与Per1
匹配,列表理解解决方案将开始失去魅力,变得有点不可读。如果不能简化配对条件,for
循环可能是一种更干净的方法。你知道吗我只想使用异常处理来忽略不符合您的模式的键:
减少行数并不一定能改进代码。你知道吗
相关问题 更多 >
编程相关推荐