是否可以在单个语句中拆分和分配字符串?
是否可以拆分字符串并将某些单词分配给一个元组?
例如:
a = "Jack and Jill went up the hill"
(user1, user2) = a.split().pick(1,3) # picks 1 and 3 element in the list.
这样的单衬可能吗?如果是的话,语法是什么。
Can a string be split and some of the words be assigned to a tuple?
For instance:
a = "Jack and Jill went up the hill"
(user1, user2) = a.split().pick(1,3) # picks 1 and 3 element in the list.
Is such a one liner possible? If so what is the syntax.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
如果你想变得更奇特,你可以使用
operator.itemgetter
:示例:
或者作为单行(没有导入):
If you want to get fancy, you could use
operator.itemgetter
:Example:
Or as a one-liner (w/o the import):
您可以执行类似的操作
,其中
_
表示我们不关心该值,而split(" ", 3)
将字符串拆分为 4 段。You can do something like this
where
_
means that we don't care of the value, andsplit(" ", 3)
split the string in 4 segments.切片支持步骤参数
,但虽然可以用 Python 编写时髦的单行代码,但它肯定不是此类练习的最佳语言。
Slicing supports a step parameter
but while it's possible to write funky oneliners in Python for sure it's not the best language for that kind of exercise.
这样就可以解决问题:
user1, user2 = a.split()[0::2][:2]
选择序列的前两个元素,从 2 in 2 开始计数。
This does the trick:
user1, user2 = a.split()[0::2][:2]
Pick the first two elements of the sequence counting from 2 in 2.
我宁愿用两行来做,但这是一行:
user1, user2 = [token for (i, token) in enumerate(a.split()) if i in (0, 2)]
这就是我会做的(只是为了可读性和减少在将来需要更改时引入错误的机会)。
I'd rather do this in two lines, but here's a one-liner:
user1, user2 = [token for (i, token) in enumerate(a.split()) if i in (0, 2)]
Here's what I would do instead (just for readability and less chance of introducing bugs if needs to be changed in the future).
我首先想到的是:
如果你想知道:
enumerate
生成元组,其中第一个元素是渐进数,第二个元素是枚举可迭代元素。编辑:正如@kindall的评论中所说,最后一步是:
但我选择不做作业只是为了让示例更切题(抱歉,如果这让某人感到困惑)。
The first that comes to my mind is:
In case you wonder:
enumerate
generates tuples with a progressive number as first element and an element of the enumerated iterable as second.EDIT: As said in the comments by @kindall, the final step would be:
but I chose not to do the assignment just to keep the example more to the point (sorry if this confused somebody).
从
Python 3.8
开始,并引入赋值表达式 (PEP 572)(:=
运算符),我们可以首先命名text.split()
表达式,然后在同一行中使用它的各个部分并创建这(user1, user2)
元组:Starting
Python 3.8
, and the introduction of assignment expressions (PEP 572) (:=
operator), we can first name thetext.split()
expression in order to then use its parts within the same line and create the(user1, user2)
tuple: