是否有用于一次性变量序列的速记语法? [英] Is there a shorthand syntax for a sequence of throwaway variables?

查看:51
本文介绍了是否有用于一次性变量序列的速记语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有这样的情况:

_, _, _, substring_1, _, substring_2 = some_string.split(',')

是否有一种速记方式来表达前三个连续下划线,表示要丢弃的值?我特别想知道是否存在这样的语法快捷方式,而不是关于完成同一任务的各种方法.

编辑 - 我对特定于 Python 2.7 的答案感兴趣.

解决方案

你可以使用 str.rsplit 有限制:

<预><代码>>>>s = 'a,b,c,d,e,f'>>>s.rsplit(',', 3) # 即从右边最多拆分三个逗号['a,b,c', 'd', 'e', 'f']>>>_, d, _, f = s.rsplit(',', 3)>>>d'd'>>>F'F'

<小时>

如果你升级到 Python 3.x,你可以使用 *_ 来吸收任意数量的元素(你会在 2.x 中得到一个 SyntaxError,虽然):

<预><代码>>>>*_, d, _, f = s.split(',')>>>d'd'>>>F'F'

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆