如何选择函数返回的 x 元组的某些元素?
我是 Python 新手。考虑返回 3 元组的函数 str.partition()
。如果我只对此元组的元素 0 和 2 感兴趣,那么从这样的元组中仅选取某些元素的最佳方法是什么?
我目前可以执行以下任一操作:
# Introduces "part1" variable, which is useless
(part0, part1, part2) = str.partition(' ')
或者:
# Multiple calls and statements, again redundancy
part0 = str.partition(' ')[0]
part2 = str.partition(' ')[2]
我希望能够执行类似这样的操作,但不能:
(part0, , part2) = str.partition(' ')
# Or:
(part0, part2) = str.partition(' ')[0, 2]
I am a newbie to Python. Consider the function str.partition()
which returns a 3-tuple. If I am interested in only elements 0 and 2 of this tuple, what is the best way to pick only certain elements out of such a tuple?
I can currently do either:
# Introduces "part1" variable, which is useless
(part0, part1, part2) = str.partition(' ')
Or:
# Multiple calls and statements, again redundancy
part0 = str.partition(' ')[0]
part2 = str.partition(' ')[2]
I would like to be able to do something like this, but cannot:
(part0, , part2) = str.partition(' ')
# Or:
(part0, part2) = str.partition(' ')[0, 2]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
下划线通常用作您不需要的东西的名称,因此类似这样的东西会起作用:
在这种特殊情况下,您可以这样做,但这不是一个很好的解决方案:
一个更深奥的解决方案:
Underscore is often used as a name for stuff you do not need, so something like this would work:
In this particular case, you could do this, but it isn't a pretty solution:
A more esoteric solution:
正确的,您不能一次性从元组列表中取出多个临时元素。
是要走的路。不用担心part1,如果你不需要它,你就不需要它。通常称其为“虚拟”或“未使用”以表明它未被使用。
你可以表现得丑陋:
在这种特殊情况下,但这会令人困惑,对其他人也不好。 ;)
Correct, you can not take several ad hoc elements out of a list of tuple in one go.
Is the way to go. Don't worry about part1, if you don't need it, you don't need it. It's common to call it "dummy" or "unused" to show that it's not used.
You CAN be ugly with:
In this specific case, but that's obfuscating and not nice towards others. ;)
我认为我前段时间问的一个问题可以帮助你:
Pythonic获取矩阵的某些行的方法
NumPy 为您提供了您想要使用元组或索引列表提取各种元素的切片语法,但我认为您不想将字符串列表转换为numpy.array 只是为了提取一些元素,所以也许你可以编写一个助手:
I think a question I asked some time ago could help you:
Pythonic way to get some rows of a matrix
NumPy gives you the slice syntax you want to extract various elements using a tuple or list of indices, but I don't think you'd like to convert you list of strings to a numpy.array just to extract a few elements, so maybe you could write a helper:
您还可以使用
str.split(' ', 1)
而不是str.partition(' ')
您将得到一个列表而不是元组,但是您不会取回分隔符
you could also use
str.split(' ', 1)
instead ofstr.partition(' ')
you'll get back a list instead of a tuple, but you won't get the separator back
我就是这样做的:
This is how I would do it: