我读过并理解浮点舍入问题,例如:
>>> sum([0.1] * 10) == 1.0
False
>>> 1.1 + 2.2 == 3.3
False
>>> sin(radians(45)) == sqrt(2) / 2
False
Run Code Online (Sandbox Code Playgroud)
我还知道如何使用math.isclose()和cmath.isclose()解决这些问题。
问题是如何将这些解决方法应用到 Python 的 match/case 语句中。我希望这个工作:
match 1.1 + 2.2:
case 3.3:
print('hit!') # currently, this doesn't match
Run Code Online (Sandbox Code Playgroud) python floating-point complex-numbers approximate structural-pattern-matching
Python 最近在 3.10 版本中发布了 match-case。问题是我们如何在 Python 中实现默认情况?我可以做if/elif,但不知道还能做什么。下面是代码:
x = "hello"
match x:
case "hi":
print(x)
case "hey":
print(x)
default:
print("not matched")
Run Code Online (Sandbox Code Playgroud)
这是我default自己添加的。我想知道在 Python 中执行此操作的方法。
我正在尝试了解Python 3.10 中新的结构模式匹配语法。我知道可以匹配这样的文字值:
def handle(retcode):
match retcode:
case 200:
print('success')
case 404:
print('not found')
case _:
print('unknown')
handle(404)
# not found
Run Code Online (Sandbox Code Playgroud)
但是,如果我重构并将这些值移动到模块级变量,则会导致错误,因为语句现在表示结构或模式而不是值:
SUCCESS = 200
NOT_FOUND = 404
def handle(retcode):
match retcode:
case SUCCESS:
print('success')
case NOT_FOUND:
print('not found')
case _:
print('unknown')
handle(404)
# File "<ipython-input-2-fa4ae710e263>", line 6
# case SUCCESS:
# ^
# SyntaxError: name capture 'SUCCESS' makes remaining patterns unreachable
Run Code Online (Sandbox Code Playgroud)
有没有办法使用 match 语句来匹配存储在变量中的值?
python switch-statement python-3.x python-3.10 structural-pattern-matching
为什么这段代码会失败:
OKAY = 200
NOT_FOUND = 404
INTERNAL_SERVER_ERROR = 500
match status:
case OKAY:
print('It worked')
case NOT_FOUND:
print('Unknown')
case INTERNAL_SERVER_ERROR:
print('Out of service')
case _:
print('Unknown code')
Run Code Online (Sandbox Code Playgroud)
它会生成以下错误消息:
File "/Users/development/Documents/handler.py", line 66
case OKAY:
^^^^
SyntaxError: name capture 'OKAY' makes remaining patterns unreachable
Run Code Online (Sandbox Code Playgroud)
该错误消息意味着什么以及如何修复代码以使其正常工作?
python syntax-error switch-statement python-3.10 structural-pattern-matching
我想转换此现有代码以使用模式匹配:
if isinstance(x, int):
pass
elif isinstance(x, str):
x = int(x)
elif isinstance(x, (float, Decimal)):
x = round(x)
else:
raise TypeError('Unsupported type')
Run Code Online (Sandbox Code Playgroud)
如何使用模式匹配编写检查,以及如何同时isinstance测试多种可能的类型?(float, Decimal)
我有一个字符串,我正在尝试针对一些正则表达式模式进行验证,并且我希望由于模式匹配在 3.10 中可用,我可能能够使用它而不是创建 if-else 块。
考虑一个字符串“validateString”,其可能值为 1021102、1.25.32、string021。
我尝试的代码如下所示。
match validateString:
case regex1:
print('Matched regex1')
case regex2:
print('Matched regex2')
case regex3:
print('Matched regex3')
Run Code Online (Sandbox Code Playgroud)
对于正则表达式 1、2 和 3,我尝试过字符串正则表达式模式以及 re.compile 对象,但它似乎不起作用。
我一直在尝试在互联网上找到这方面的示例,但似乎找不到任何涵盖正则表达式模式匹配与新的 python 模式匹配的示例。
关于如何让它发挥作用有什么想法吗?
谢谢!
我需要将 gettext 翻译添加到代码中的所有字符串文字中,但它不适用于 case 语句中的文字。
这次失败的尝试给出SyntaxError: Expected ':':
from gettext import gettext as _
direction = input(_('Enter a direction: ')) # <-- This works
match direction:
case _('north'): # <-- This fails
adj = 1, 0
case _('south'):
adj = -1, 0
case _('east'):
adj = 0, 1
case _('west'):
adj = 0, -1
case _:
raise ValueError(_('Unknown direction'))
Run Code Online (Sandbox Code Playgroud)
该错误是什么意思以及如何标记翻译方向?
我正在尝试使用 SPM 来确定某种类型是intan 还是str.
下面的代码:
from typing import Type
def main(type_to_match: Type):
match type_to_match:
case str():
print("This is a String")
case int():
print("This is an Int")
case _:
print("\nhttps://en.meming.world/images/en/0/03/I%27ve_Never_Met_This_Man_In_My_Life.jpg")
if __name__ == "__main__":
test_type = str
main(test_type)
Run Code Online (Sandbox Code Playgroud)
返回https://en.meming.world/images/en/0/03/I%27ve_Never_Met_This_Man_In_My_Life.jpg
我找到的大多数文档都讨论了如何测试某个变量是否是某个类型的实例。但不是如何测试类型是否属于某种类型。
关于如何使其发挥作用有什么想法吗?
这个例子在使用模式匹配时被讨论为可能的“陷阱”:
NOT_FOUND = 400
retcode = 200
match retcode:
case NOT_FOUND:
print('not found')
print(f'Current value of {NOT_FOUND=}')
Run Code Online (Sandbox Code Playgroud)
这是使用结构模式匹配意外捕获的示例。它给出了这个意想不到的输出:
not found
Current value of NOT_FOUND=200
Run Code Online (Sandbox Code Playgroud)
同样的问题以其他形式出现:
match x:
case int():
pass
case float() | Decimal():
x = round(x)
case str:
x = int(x)
Run Code Online (Sandbox Code Playgroud)
在这个例子中,str需要有括号,str(). 没有它们,它“捕获”并且str内置类型被替换为x的值。
是否有防御性编程实践可以帮助避免这些问题并提供早期检测?
python defensive-programming python-3.10 structural-pattern-matching
这与新的 Python 3.10 beta 和新语法有关match。有没有什么方法可以检查模式是否简单地包含在可迭代中?最明显的解决方案是简单地在两侧放置两个通配符,但这会SyntaxError由于来自可迭代解包的解包语法而引发。
有没有可能的方法来做到这一点?注意:在示例中使用包装类之类的东西numbers
就可以了,只要它可以使用匹配块并且至少具有一定的可读性,但我已经尝试过这一点,但没有取得太大成功
例子:
numbers = [1, 2, 3, 5, 7, 8, 9] #does not have to be a list, could be a class if needed
match numbers:
# this just raises a SyntaxError, but I need a way to do something equivalent to this
case [*_, (5 | 6), *_]:
print("match!")
Run Code Online (Sandbox Code Playgroud) python iterable iterable-unpacking python-3.10 structural-pattern-matching
python ×10
structural-pattern-matching ×10
python-3.10 ×8
approximate ×1
gettext ×1
isinstance ×1
iterable ×1
python-3.x ×1
regex ×1
syntax-error ×1