繁体   English   中英

就地更新列表

[英]Updating list in-place

我有一个字符串列表,其中一些以新行符号结尾。 我想通过从以它结尾的字符串中删除\\ n来修改此列表。 为此,我使用以下代码:

aList = ['qwerttyy\n', '123454\n', 'zxcv']

for s in aList:
    if s.endswith('\n'):
    s = s[: -1]
        print(s)

输出如下:

qwerttyy
    123454
    >>> aList
    ['qwerttyy\n', '123454\n', 'zxcv']

因此,尽管list是可变对象,但原始列表没有改变。 这种行为的原因是什么?

您可以使用切片分配和列表理解:

>>> foo = aList = ['qwerttyy\n', '123454\n', 'zxcv']
>>> aList[:] = [s[:-1] if s.endswith('\n') else s for s in aList]
>>> foo                         #All references are affected.
['qwerttyy', '123454', 'zxcv']
>>> aList
['qwerttyy', '123454', 'zxcv']

您的代码不起作用,因为它相当于:

s = aList[0]
if s.endswith('\n'):
    s = s[: -1]
s = aList[1]
if s.endswith('\n'):
    s = s[: -1]
...

即您正在更新变量s ,而不是实际的列表项

因为for循环会创建字符串的副本。

您可以使用: [s[:-1] if s.endswith('\\n') else s for s in aList]

也许这更简单,虽然它也会删除空格。 [s.strip() for s in aList]

试试这个

>>> aList = ['qwerttyy\n', '123454\n', 'zxcv']
>>> aList = [x[:-1] if x.endswith('\n') else x for x in aList]
>>> aList
['qwerttyy', '123454', 'zxcv']

使用list comprehensionstr.rstrip

>>> aList = ['qwerttyy\n', '123454\n', 'zxcv']
>>> [s.rstrip('\n') for s in aList]
['qwerttyy', '123454', 'zxcv']

以上将创建新列表。 要修改原始列表,请使用切片( list[:] = ... ):

>>> aList
['qwerttyy\n', '123454\n', 'zxcv']
>>> aList[:] = [s.rstrip('\n') for s in aList]
>>> aList
['qwerttyy', '123454', 'zxcv']

str.rstrip返回从不同的结果[:-1]当tehre多个尾随换行符:

>>> 'qwerttyy\n\n'.rstrip('\n')
'qwerttyy'
>>> 'qwerttyy\n\n'[:-1]
'qwerttyy\n'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM