Sam*_*adi 4 python python-3.x iterable-unpacking
我经常对Python的可迭代解包缺乏灵活性感到沮丧.请看以下示例:
a, b = "This is a string".split(" ", 1)
Run Code Online (Sandbox Code Playgroud)
工作良好.正如预期的那样a包含"This"和b包含"is a string".现在让我们试试这个:
a, b = "Thisisastring".split(" ", 1)
Run Code Online (Sandbox Code Playgroud)
现在,我们得到一个ValueError:
ValueError: not enough values to unpack (expected 2, got 1)
Run Code Online (Sandbox Code Playgroud)
不理想,当期望的结果是"Thisisastring"在a和None或更好,但""在b.
有很多黑客可以解决这个问题.我见过的最优雅的是:
a, *b = mystr.split(" ", 1)
b = b[0] if b else ""
Run Code Online (Sandbox Code Playgroud)
不漂亮,并且对Python新手来说非常困惑.
那么最恐怖的方式是什么?将返回值存储在变量中并使用if块?该*varname黑客?别的什么?
这看起来非常适合str.partition:
>>> a, _, b = "This is a string".partition(" ")
>>> a
'This'
>>> b
'is a string'
>>> a, _, b = "Thisisastring".partition(" ")
>>> a
'Thisisastring'
>>> b
''
>>>
Run Code Online (Sandbox Code Playgroud)