解释不熟悉的python语法返回lis

2024-10-05 17:39:16 发布

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

我完全理解这个表达式的右边在做什么。 但它又回到了什么样的状态?换句话说,左边在做什么?你知道吗

[records, remainder] = ''.join([remainder, tmp]).rsplit(NEWLINE,1)

我不熟悉那种语法。你知道吗

remainder在此行上方定义为空字符串:

remainder = ''

但是records在函数的任何地方都没有定义。你知道吗

从上下文来看,它应该是积累流媒体内容,但我不明白如何。你知道吗


Tags: 函数字符串内容定义表达式状态地方newline
3条回答

它首先使用空字符串作为连接符joinsremainder的内容与tmp的内容连接起来。你知道吗

''.join([...])

然后它splits从右边连接,使用NEWLINE作为拆分器,只执行一次拆分,也就是说,它返回两个值,一个从NEWLINE的开头到第一次出现,另一个从那里到结尾。你知道吗

.rsplit(NEWLINE, 1)

最后,它使用tuple unpacking将第一个值赋给records,将第二个值赋给remainder。你知道吗

a, b = (c, d)

records获取rsplit返回值的第一个元素。remainder是第二个。你知道吗

% python
Python 2.7 (r27:82500, Sep 16 2010, 18:02:00) 
[GCC 4.5.1 20100907 (Red Hat 4.5.1-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> foo = [3, 9]
>>> [records, remainder] = foo
>>> records
3
>>> remainder
9
>>> foo = [3, 9, 10]
>>> [records, remainder] = foo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack

实际上,你不需要在[records, remainder]周围加方括号,但它们很有风格。你知道吗

不确定流媒体内容,但您可以很容易地自己尝试:

>>> a = 'abc'
>>> b = '\ndef\nghi'
>>> c = (a + b).rsplit('\n', 1)
#['abc\ndef', 'ghi']

然后它使用解包来分配两个变量(应该写为):

fst, snd = c

(这些[]是多余的)

相关问题 更多 >