是否有用于一次性变量序列的速记语法? [英] Is there a shorthand syntax for a sequence of throwaway variables?
问题描述
假设您有这样的情况:
_, _, _, substring_1, _, substring_2 = some_string.split(',')
是否有一种速记方式来表达前三个连续下划线,表示要丢弃的值?我特别想知道是否存在这样的语法快捷方式,而不是关于完成同一任务的各种方法.
编辑 - 我对特定于 Python 2.7 的答案感兴趣.
你可以使用 str.rsplit
有限制:
<小时>
如果你升级到 Python 3.x,你可以使用 *_
来吸收任意数量的元素(你会在 2.x 中得到一个 SyntaxError
,虽然):
Let's say you have a situation like this:
_, _, _, substring_1, _, substring_2 = some_string.split(',')
Is there a shorthand way of expressing those first three sequential underscores, representing values that are to be discarded? I'm specifically wondering if such a syntactic shortcut exists, not about various ways to accomplish the same task.
Edit - I'm interested in a Python 2.7-specific answer.
You could just use str.rsplit
with a limit:
>>> s = 'a,b,c,d,e,f'
>>> s.rsplit(',', 3) # i.e. split on at most three commas, from the right
['a,b,c', 'd', 'e', 'f']
>>> _, d, _, f = s.rsplit(',', 3)
>>> d
'd'
>>> f
'f'
If you upgrade to Python 3.x, you can use *_
to absorb an arbitrary number of elements (you'll get a SyntaxError
in 2.x, though):
>>> *_, d, _, f = s.split(',')
>>> d
'd'
>>> f
'f'
这篇关于是否有用于一次性变量序列的速记语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!