当只能分配a和b时,如何在不崩溃的情况下执行a,b,c=x.split(“”)?

2024-10-01 01:32:59 发布

您现在位置:Python中文网/ 问答频道 /正文

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

如果我希望它是2个或3个单词并且仍然能够打印a,那么应该使用什么代码?你知道吗


Tags: inpymostlinecallterminalfilesplit
3条回答

如果您实际上不需要bc,可以执行以下操作:

>>> sentence = 'munching macdonalds'
>>> first, rest = sentence.split(' ', 1)
>>> first
'munching'
>>> rest
'macdonalds'

它使用str.split(参见the docs)的maxsplit参数来限制第一个空间上的分裂。你知道吗

然后,您可以执行例如if ' ' in rest:来确定是否可以进一步拆分第二部分。你知道吗


如果您使用的是Python3,那么可以使用*表示法来完成整个拆分,使first成为字符串,rest成为列表:

>>> sentence = 'munching macdonalds'
>>> first, *rest = sentence.split(' ')
>>> first
'munching'
>>> rest
['macdonalds']
>>> sentence = 'foo bar baz'
>>> first, *rest = sentence.split(' ')
>>> first
'foo'
>>> rest
['bar', 'baz']

这个版本很容易重复,并在左侧为所有变量提供值,以防您决定以后使用它们(不仅仅是a)。请注意,它也不会修改原始列表,以便以后可以根据需要使用。你知道吗

def pad(iterable, length=0, padding=None):
    li = list(iterable)  # Generate new list from `iterable`.
    li.extend([padding] * (length - len(li)))  # Negative value generates empty list...
    return li

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 = pad(range(4), 3)
assert a == [0, 1, 2, 3]

更新的答案

我在写了我的第一篇文章后就想到了这一点,然后我的作者也指出了这一点 在评论中指出,将此作为列表生成可能是危险的。如果…怎么办 我们想把它填充到,比如说,1E30个元素左右?这是函数作为 发电机。你知道吗

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]

谢谢你,麦考特!你知道吗

split()返回一个列表。因此,应将其用作:

a = "munching mcdonalds"
b = a.split(" ")

>>>b
['munching', 'mcdonalds']
>>>b[0]
'munching' 
>>>b[1]
'mcdonalds'

相关问题 更多 >