[英]Is it possible to assign a default value when unpacking?
I have the following: 我有以下内容:
>>> myString = "has spaces"
>>> first, second = myString.split()
>>> myString = "doesNotHaveSpaces"
>>> first, second = myString.split()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: need more than 1 value to unpack
I would like to have second
default to None
if the string does not have any white space. 如果字符串没有任何空格,我希望
second
默认为None
。 I currently have the following, but am wondering if it can be done in one line: 我目前有以下内容,但我想知道是否可以在一行中完成:
splitted = myString.split(maxsplit=1)
first = splitted[0]
second = splitted[1:] or None
May I suggest you to consider using a different method, ie partition
instead of split
: 我建议你考虑使用不同的方法,即
partition
而不是split
:
>>> myString = "has spaces"
>>> left, separator, right = myString.partition(' ')
>>> left
'has'
>>> myString = "doesNotHaveSpaces"
>>> left, separator, right = myString.partition(' ')
>>> left
'doesNotHaveSpaces'
If you are on python3, you have this option available: 如果您使用的是python3,则可以使用以下选项:
>>> myString = "doesNotHaveSpaces"
>>> first, *rest = myString.split()
>>> first
'doesNotHaveSpaces'
>>> rest
[]
A general solution would be to chain
your iterable with a repeat
of None
values and then use an islice
of the result: 一般的解决方案是使用
repeat
的None
值chain
你的iterable,然后使用结果的islice
:
from itertools import chain, islice, repeat
none_repat = repeat(None)
example_iter = iter(range(1)) #or range(2) or range(0)
first, second = islice(chain(example_iter, none_repeat), 2)
this would fill in missing values with None
, if you need this kind of functionality a lot you can put it into a function like this: 这将用
None
填充缺失值,如果你需要很多这样的功能,你可以把它放到这样的函数中:
def fill_iter(it, size, fill_value=None):
return islice(chain(it, repeat(fill_value)), size)
Although the most common use is by far for strings which is why str.partition
exists. 虽然最常见的用途是字符串,这就是
str.partition
存在的原因。
Here's one general solution to unpack tuple and use default value if tuple is shorter than expected: 这是解压缩元组的一个通用解决方案,如果元组比预期短,则使用默认值:
unpacker = lambda x,y=1,z=2:(x,y,z)
packed = (8,5)
a,b,c = unpacker(*packed)
print(a,b,c) # 8 5 2
packed = (8,)
a,b,c = unpacker(*packed)
print(a,b,c) # 8 1 2
You could try this: 你可以试试这个:
NUM2UNPACK=2
parts = myString.split()
first, second = parts+[None]*(NUM2UNPACK-(len(parts)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.