计算两个相同的数字时得到空输出并且无法更改带有正则表达式的字典中的键名
Getting an empty output when calculating two same numbers and unable to change key name in dict w/ Regex
编辑:我能够通过添加一个条件来弄清楚这个问题的第一部分,如果 cost
和 paid
相同并且匹配 [=14= 中的键值] 然后将其添加到字典中。
如果标题令人困惑,我深表歉意。基本上,我正在编写一个函数,它接受一个数字作为项目成本,第二个作为你支付的金额。然后它会告诉你纸币和硬币的变化。
def right_change(cost, paid):
money = {
" bill" : 20,
" bill" : 10,
" bill" : 5,
" bill": 1,
"quarter": 0.25,
"dime" : 0.10,
"nickel": 0.05,
"penny": 0.01
}
amount = paid - cost
change = {}
for item in money:
while amount >= money[item]:
amount -= money[item]
amount = float(f'{amount:.2f}')
if item not in change:
change[item] = 1
else:
change[item] += 1
当我使用 (5.40, 20) --> { bill: 1, bill: 4, quarter: 2, dime: 1}
等浮点数时,我得到了预期的输出
但是如果我使用像 (20, 20)
这样的确切数字,当我想要 { bill: 1}
时,它会 return 一个空的 object
如果名称的数量超过 1,我还尝试将名称更改为复数。为了减少冗余并为每个单词输入条件,我尝试使用正则表达式:
def plurals(dict):
new_dict = {}
for item in dict:
if dict[item] > 1 and re.match('/[^y]$/gm', item):
new_dict[item+"s"] = dict[item]
if re.match('p', item):
new_dict['pennies'] = dict[item]
else:
new_dict[item] = dict[item]
return new_dict
它仍然会输出更改,但不会更改任何内容。任何帮助表示赞赏!我花了好几个小时想弄清楚这个问题。
关于更名问题:
def set_to_plural_if_more_than_one(old_dict):
new_dict = {}
for item in old_dict:
if old_dict[item] > 1:
if item[-1] == "y":
new_dict[item[:-1] + "ies"] = old_dict[item]
else:
new_dict[item + "s"] = old_dict[item]
else:
new_dict[item] = old_dict[item]
return new_dict
你可以使用正则表达式,但我觉得在这种情况下它有点矫枉过正,因为你只是在区分你知道的一些基本字符串,而不是搜索任何高级模式。
另外,一般来说,我会避免在代码中覆盖 pythons 内置函数的名称,例如 dict
作为变量或参数名称,因为它们会导致奇怪的,有时难以调试的行为。
编辑:我能够通过添加一个条件来弄清楚这个问题的第一部分,如果 cost
和 paid
相同并且匹配 [=14= 中的键值] 然后将其添加到字典中。
如果标题令人困惑,我深表歉意。基本上,我正在编写一个函数,它接受一个数字作为项目成本,第二个作为你支付的金额。然后它会告诉你纸币和硬币的变化。
def right_change(cost, paid):
money = {
" bill" : 20,
" bill" : 10,
" bill" : 5,
" bill": 1,
"quarter": 0.25,
"dime" : 0.10,
"nickel": 0.05,
"penny": 0.01
}
amount = paid - cost
change = {}
for item in money:
while amount >= money[item]:
amount -= money[item]
amount = float(f'{amount:.2f}')
if item not in change:
change[item] = 1
else:
change[item] += 1
当我使用 (5.40, 20) --> { bill: 1, bill: 4, quarter: 2, dime: 1}
等浮点数时,我得到了预期的输出
但是如果我使用像 (20, 20)
这样的确切数字,当我想要 { bill: 1}
如果名称的数量超过 1,我还尝试将名称更改为复数。为了减少冗余并为每个单词输入条件,我尝试使用正则表达式:
def plurals(dict):
new_dict = {}
for item in dict:
if dict[item] > 1 and re.match('/[^y]$/gm', item):
new_dict[item+"s"] = dict[item]
if re.match('p', item):
new_dict['pennies'] = dict[item]
else:
new_dict[item] = dict[item]
return new_dict
它仍然会输出更改,但不会更改任何内容。任何帮助表示赞赏!我花了好几个小时想弄清楚这个问题。
关于更名问题:
def set_to_plural_if_more_than_one(old_dict):
new_dict = {}
for item in old_dict:
if old_dict[item] > 1:
if item[-1] == "y":
new_dict[item[:-1] + "ies"] = old_dict[item]
else:
new_dict[item + "s"] = old_dict[item]
else:
new_dict[item] = old_dict[item]
return new_dict
你可以使用正则表达式,但我觉得在这种情况下它有点矫枉过正,因为你只是在区分你知道的一些基本字符串,而不是搜索任何高级模式。
另外,一般来说,我会避免在代码中覆盖 pythons 内置函数的名称,例如 dict
作为变量或参数名称,因为它们会导致奇怪的,有时难以调试的行为。