a = munching mcdonalds
a,b,c = a.split(" ")
Traceback (most recent call last):
File "terminal.py", line 25, in <module>
a,b,c = a.split(" ")
ValueError: need more than 1 value to unpack
def pad(iterable, length=0, padding=None):
for element in iterable:
yield element
for _ in range(length - len(iterable)):
yield padding
sentence = 'munching mcdonalds'
a, b, c = pad(sentence.split(), 3)
assert (a, b, c) == ('munching', 'mcdonalds', None)
a, b, c, d = pad(range(3), 4)
assert (a, b, c, d) == (0, 1, 2, None)
a = list(pad(range(4), 3))
assert a == [0, 1, 2, 3]
如果您实际上不需要
b
或c
,可以执行以下操作:它使用
str.split
(参见the docs)的maxsplit
参数来限制第一个空间上的分裂。你知道吗然后,您可以执行例如
if ' ' in rest:
来确定是否可以进一步拆分第二部分。你知道吗如果您使用的是Python3,那么可以使用
*
表示法来完成整个拆分,使first
成为字符串,rest
成为列表:这个版本很容易重复,并在左侧为所有变量提供值,以防您决定以后使用它们(不仅仅是
a
)。请注意,它也不会修改原始列表,以便以后可以根据需要使用。你知道吗更新的答案
我在写了我的第一篇文章后就想到了这一点,然后我的作者也指出了这一点 在评论中指出,将此作为列表生成可能是危险的。如果…怎么办 我们想把它填充到,比如说,1E30个元素左右?这是函数作为 发电机。你知道吗
谢谢你,麦考特!你知道吗
split()
返回一个列表。因此,应将其用作:相关问题 更多 >
编程相关推荐