Answers:
它被认为是不良形式。如果需要保留对列表的现有引用,请使用列表理解来代替切片分配。
a = [1, 3, 5]
b = a
a[:] = [x + 2 for x in a]
print(b)
print b执行该语句时,您可以知道是否a就地进行了修改,而不是替换了。另一种可能性是print b is a查看它们是否仍然都引用同一对象。
由于下面的循环仅修改已经看到的元素,因此可以接受:
a = ['a',' b', 'c ', ' d ']
for i, s in enumerate(a):
a[i] = s.strip()
print(a) # -> ['a', 'b', 'c', 'd']
不同于:
a[:] = [s.strip() for s in a]
尽管它确实需要更多的索引操作,但它不需要创建临时列表和分配临时列表来替换原始列表。
注意:尽管您可以通过这种方式修改条目,但是您不能在不改变list遇到问题的风险的情况下更改其中的项数。
这是我的意思的示例-从该点开始删除条目会使索引混乱:
b = ['a', ' b', 'c ', ' d ']
for i, s in enumerate(b):
if s.strip() != b[i]: # leading or trailing whitespace?
del b[i]
print(b) # -> ['a', 'c '] # WRONG!
(结果是错误的,因为它没有删除应有的所有项目。)
更新资料
由于这是一个相当普遍的答案,因此,这是有效地“就地”删除条目的方法(即使这不是确切的问题):
b = ['a',' b', 'c ', ' d ']
b[:] = [entry for entry in b if entry.strip() == entry]
print(b) # -> ['a'] # CORRECT
for i in a?这是非常违反直觉的,似乎与其他语言不同,并且导致我的代码中的错误,我不得不长时间进行调试。Python教程甚至没有提到它。虽然一定有一定理由吗?
a[i]和s)?我宁愿做a[i] = a[i].strip()。
a[i] = s.strip()仅执行一次索引操作。
enumerate(b)在每次迭代中都执行索引操作,而您正在使用进行另一个操作a[i] =。AFAIK不可能在Python中通过每个循环迭代仅执行1次索引操作来实现此循环:(
还有一个for循环变量,对我来说比使用enumerate()更干净:
for idx in range(len(list)):
list[idx]=... # set a new value
# some other code which doesn't let you use a list comprehension
range(len(list))在Python中使用类似代码的味道。
enumerate是生成器,所以它不会创建一个元组列表,它会在遍历该列表时一次创建一个元组。判断哪个较慢的唯一方法是timeit。
Jemshit Iskenderov和Ignacio Vazquez-Abrams给出的答案确实很好。这个例子可以进一步说明:
a)给出了带有两个向量的列表;
b)您想遍历列表并反转每个数组的顺序
假设您有
v = np.array([1, 2,3,4])
b = np.array([3,4,6])
for i in [v, b]:
i = i[::-1] # this command does not reverse the string
print([v,b])
你会得到
[array([1, 2, 3, 4]), array([3, 4, 6])]
另一方面,如果您这样做
v = np.array([1, 2,3,4])
b = np.array([3,4,6])
for i in [v, b]:
i[:] = i[::-1] # this command reverses the string
print([v,b])
结果是
[array([4, 3, 2, 1]), array([6, 4, 3])]
从您的问题尚不清楚,确定删除哪些字符串的标准是什么,但是如果您有或可以列出要删除的字符串,则可以执行以下操作:
my_strings = ['a','b','c','d','e']
undesirable_strings = ['b','d']
for undesirable_string in undesirable_strings:
for i in range(my_strings.count(undesirable_string)):
my_strings.remove(undesirable_string)
将my_strings更改为['a','c','e']