【发布时间】:2019-03-29 05:30:48
【问题描述】:
我假设Python 中的 foreach 样式结构将允许我像在C# 中那样更新我的列表。没有。
经过一番调查,我发现 foreach 样式构造中Python 中使用的变量不是引用,而是一个单独的标量变量,因此我无法使用它来更新我的容器。有没有办法使用 foreach 样式更新容器?
这是一些演示我的问题的代码:
inputString = " Type X Widgets , 25, 14.20 , Type Y Widgets , 4 , 1.12 "
inputList = inputString.split(',')
print(inputList) # Now I need to get rid of whitespace on the ends of each element
# The foreach-style does NOT update inputList
for element in inputList:
element = element.strip()
print(element, end=",") # element contains the stripped string as I wanted
print()
print(inputList) # the whitespace on the ends of the elements is still there
# The for-style with subscripts DOES update inputList
for i in range(len(inputList)):
inputList[i] = inputList[i].strip()
print(inputList[i], end=",") # inputList[i] contains the stripped string as I wanted
print()
print(inputList) # it finally contains the stripped strings with no whitespace on the ends
这是上面的输出:
[' Type X Widgets ', ' 25', ' 14.20 ', ' Type Y Widgets ', ' 4 ', ' 1.12 ']
Type X Widgets,25,14.20,Type Y Widgets,4,1.12,
[' Type X Widgets ', ' 25', ' 14.20 ', ' Type Y Widgets ', ' 4 ', ' 1.12 ']
Type X Widgets,25,14.20,Type Y Widgets,4,1.12,
['Type X Widgets', '25', '14.20', 'Type Y Widgets', '4', '1.12']
第一个 for 循环不会更新容器。第二个可以。在这个简单的情况下,我必须使用下标并不重要,但我真的希望能够在下标根本不起作用时使用 foreach 样式来更新更复杂类型的容器。
我可以在C# 中做到这一点,这是一个非常强大的工具。这在Python 中是否可能通过除了我在第一个循环中尝试的之外做一些事情? (如果是这样,我想它会涉及使用指针。Python 甚至有指针吗?)
【问题讨论】:
-
“我可以在 Java 和 C# 中做到这一点,而且它是一个非常强大的工具” - 我不确定 C#,但你绝对不能在 Java 中做到这一点。
-
显然你可以在 C# 中,by declaring the loop variable with
ref. -
Python 没有指针。如果你给出一个更复杂类型的容器的例子会很有帮助,但无论如何,你将总是需要使用一个mutator方法来改变一个对象。 python中的赋值永远不会发生变化。因此,如果您提供一个您想到的容器示例,也许会更有帮助,我们可以向您展示 Python 的做法?
-
“我发现 Python 中在 foreach 样式结构中使用的变量不是引用,而是一个单独的标量变量”我不确定您所说的“单独的标量变量”是什么意思与引用相反,但 Python 变量的行为类似于引用(即它们不会在赋值时创建副本)
-
对于从 C 等语言开始使用 Python 的人来说,这绝对是必不可少的读物,顺便说一句:nedbatchelder.com/text/names.html 它是由 StackOverflow 的传奇人物 Ned Batchelder 编写的。但是,如果来自 C,您实际上可以将 Python 变量视为指向 PyObject 结构的指针,除非您不能直接取消引用它们,而改变它们的唯一方法是使用这些 PyObject 上的方法。实际上,您可以将
some_object[i] = x视为some_object.__setitem__(i, x)的语法糖
标签: python list for-loop foreach containers