我正在寻找创建一个带有包含通配符的键的 Python 字典。这可能吗?
目前,我正在创建一个程序来查找与特定类型的评分相关的分值。例如,与'Four-of-a-Kind'
或'Straight'
关联的点值是多少。问题是有几种类型的四种(即 'Four-of-a-Kind-(1)', 'Four-of-a-Kind-(2)',...
) 都具有相同的点值。
这是我目前所拥有的:
mode_value = {'1-Spot': 100,
'5-Spot': 500,
'Three-of-a-Kind-(1)': 300,
'Three-of-a-Kind-(2)': 200,
'Three-of-a-Kind-(3)': 300,
'Three-of-a-Kind-(4)': 400,
'Three-of-a-Kind-(5)': 500,
'Three-of-a-Kind-(6)': 600,
'Four-of-a-Kind-(1)': 1000,
'Four-of-a-Kind-(2)': 1000,
'Four-of-a-Kind-(3)': 1000,
'Four-of-a-Kind-(4)': 1000,
'Four-of-a-Kind-(5)': 1000,
'Four-of-a-Kind-(6)': 1000,
'Five-of-a-Kind-(1)': 2000,
'Five-of-a-Kind-(2)': 2000,
'Five-of-a-Kind-(3)': 2000,
'Five-of-a-Kind-(4)': 2000,
'Five-of-a-Kind-(5)': 2000,
'Five-of-a-Kind-(6)': 2000,
...
'Straight': 1500 }
给定字典有一个包含评分模式的键,它返回该特定模式的值:
In [1]: mode_value['Four-of-a-Kind-(3)']
Out [1]: 1000
这会产生大量的重复。例如,当我到达 'Four-of-a-Kind-w/Pair-(*)'
时,它可以与任何六种类型或四种类型中的任何一种六种类型中的两种类型,都产生相同的分数。
这是我想要的东西:
mode_value = {'1-Spot': 100,
'5-Spot': 500,
'Three-of-a-Kind-(1)': 300,
'Three-of-a-Kind-(2)': 200,
'Three-of-a-Kind-(3)': 300,
'Three-of-a-Kind-(4)': 400,
'Three-of-a-Kind-(5)': 500,
'Three-of-a-Kind-(6)': 600,
'Four-of-a-Kind-(*)': 1000,
'Five-of-a-Kind-(*)': 2000,
'Six-of-a-Kind-(*)': 3000,
'Three-Pairs-(*)': 1500,
'Two-Triplets-(*)': 2500,
'Four-of-a-Kind-w/Pair-(*)': 1500,
'Straight': 1500 }
到目前为止我所看到的:
搜索表单只会提出有关在查询字典时使用通配符的问题,而不是创建字典。 (即 Python, accessing dictionary with wildcards )
Another question used comprehension to create a similar effect (i.e. Creating a Python dictionary using a comprehension),但我觉得鉴于 Python 中的大部分内容,必须有一种更简单的方法。
同样,这在 Python 中可行吗?这将大大简化为其他类型的评分编写这部分代码的类似部分。
最佳答案
首先,您应该分别拥有这些值(并且没有括号):
type = 'Three-of-a-Kind'
mode = '1'
(这可以通过解析或以不同方式存储数据来完成。)
在那之后,您可以稍微不同地看待问题。
您希望从匹配 type-(mode)
或 type-(*)
的键中获取值。解决方案是在匹配时简单地使用正则表达式,as shown here .
您的案例中的代码可能是:
for key in dict:
if re.match(type + r'-\((' + mode + r'|\*)\)', key):
print(dict[key])
这将匹配您当前的 key 格式。
它简化了正则表达式,将格式更改为 Four-of-a-Kind1
(其中 Four-of-a-Kind*
是通配符版本):
for key in dict:
if re.match(type + r'(' + mode + r'|\*)', key):
print(dict[key])
关于python - 使用带通配符的键创建 Python 字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37604019/