简体   繁体   English

如何遍历列表并使用.strip()更新值

[英]How to iterate through a list and update values with .strip()

If I have a list of strings and want to eliminate leading and trailing whitespaces from it, how can I use .strip() effectively to accomplish this? 如果我有一个字符串列表,并且想从中消除开头和结尾的空格,那么如何有效地使用.strip()来完成此操作?

Here is my code (python 2.7): 这是我的代码(python 2.7):

for item in myList:
    item = item.strip()
    print item

for item in myList:
    print item

The changes don't preserve from one iteration to the next. 从一次迭代到下一次迭代,更改不会保留。 I tried using map as suggested here ( https://stackoverflow.com/a/7984192 ) but it did not work for me. 我尝试按照此处的建议使用地图( https://stackoverflow.com/a/7984192 ),但它对我不起作用。 Please help. 请帮忙。

Note, this question is useful: 注意,这个问题很有用:

  1. An answer does not exist already 答案不存在
  2. It covers a mistake someone new to programming / python might make 它涵盖了一个刚接触编程/ python的人可能犯的错误
  3. Its title covers search cases both general (how to update values in a list) and specific (how to do this with .strip()). 它的标题涵盖常规(如何更新列表中的值)和特定(如何使用.strip()实现)的搜索用例。
  4. It addresses previous work, in particular the map solution, which would not work for me. 它解决了以前的工作,特别是地图解决方案,但对我来说不起作用。

I'm guessing you tried: 我猜你尝试过:

map(str.strip, myList)

That creates a new list and returns it, leaving the original list unchanged. 这将创建一个新列表并返回它,而原始列表保持不变。 If you want to interact with the new list, you need to assign it to something. 如果要与新列表交互,则需要将其分配给某些对象。 You could overwrite the old value if you want. 如果需要,您可以覆盖旧值。

myList = map(str.strip, myList)

You could also use a list comprehension: 您还可以使用列表理解:

myList = [item.strip() for item in myList]

Which many consider a more "pythonic" style, compared to map . map相比,许多人认为这是更“ pythonic”的风格。

I'm answering my own question here in the hopes that it saves someone from the couple hours of searching and experimentation it took me. 我在这里回答我自己的问题,希望它可以使某人从花了我几个小时的搜索和实验中解脱出来。

As it turns out the solution is fairly simple: 事实证明,解决方案非常简单:

index = 0
for item in myList:
    myList[index] = item.strip()
    index += 1

for item in myList:
    print "'"+item+"'"

Single quotes are concatenated at the beginning/end of each list item to aid detection of trailing/leading whitespace in the terminal. 单引号串联在每个列表项的开头/结尾,以帮助检测终端中的尾随/前导空格。 As you can see, the strings will now be properly stripped. 如您所见,现在将正确剥离字符串。

To update the values in the list we need to actually access the element in the list via its index and commit that change. 要更新列表中的值,我们需要通过索引实际访问列表中的元素并提交更改。 I suspect the reason is because we are passing by value (passing a copy of the value into item) instead of passing by reference (directly accessing the underlying list[item]) when we declare the variable "item," whose scope is local to the for loop. 我怀疑原因是因为当我们声明变量“ item”时,我们通过值传递(将值的副本传递给item),而不是通过引用传递(直接访问基础列表[item]),变量的作用域是局部的for循环。

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

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