在for循环中如何修改列表项?

问题:在for循环中如何修改列表项?

现在,我知道在迭代循环中修改列表是不安全的。但是,假设我有一个字符串列表,并且我想剥离字符串本身。替换可变值是否算作修改?

Now I know that it is not safe to modify the list during an iterative looping. However, suppose I have a list of strings, and I want to strip the strings themselves. Does replacement of mutable values count as modification?


回答 0

它被认为是不良形式。如果需要保留对列表的现有引用,请使用列表理解来代替切片分配。

a = [1, 3, 5]
b = a
a[:] = [x + 2 for x in a]
print(b)

It’s considered poor form. Use a list comprehension instead, with slice assignment if you need to retain existing references to the list.

a = [1, 3, 5]
b = a
a[:] = [x + 2 for x in a]
print(b)

回答 1

由于下面的循环仅修改已经看到的元素,因此可以接受:

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

Since the loop below only modifies elements already seen, it would be considered acceptable:

a = ['a',' b', 'c ', ' d ']

for i, s in enumerate(a):
    a[i] = s.strip()

print(a) # -> ['a', 'b', 'c', 'd']

Which is different from:

a[:] = [s.strip() for s in a]

in that it doesn’t require the creation of a temporary list and an assignment of it to replace the original, although it does require more indexing operations.

Caution: Although you can modify entries this way, you can’t change the number of items in the list without risking the chance of encountering problems.

Here’s an example of what I mean—deleting an entry messes-up the indexing from that point on:

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!

(The result is wrong because it didn’t delete all the items it should have.)

Update

Since this is a fairly popular answer, here’s how to effectively delete entries “in-place” (even though that’s not exactly the question):

b = ['a',' b', 'c ', ' d ']

b[:] = [entry for entry in b if entry.strip() == entry]

print(b)  # -> ['a']  # CORRECT

回答 2

还有一个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

One more for loop variant, looks cleaner to me than one with 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

回答 3

只要不更改将元素添加/删除到列表中,在迭代列表时修改每个元素就可以了。

您可以使用列表推导:

l = ['a', ' list', 'of ', ' string ']
l = [item.strip() for item in l]

或者只是做C-stylefor循环:

for index, item in enumerate(l):
    l[index] = item.strip()

Modifying each element while iterating a list is fine, as long as you do not change add/remove elements to list.

You can use list comprehension:

l = ['a', ' list', 'of ', ' string ']
l = [item.strip() for item in l]

or just do the C-style for loop:

for index, item in enumerate(l):
    l[index] = item.strip()

回答 4

不,如果您可以通过这种方式更改字符串,则不会更改列表的“内容”。但是在Python中它们不是可变的。任何字符串操作都将返回一个新字符串。

如果您有一个已知的可变对象列表,那么只要不更改列表的实际内容,就可以执行此操作。

因此,您将需要进行某种映射。如果使用生成器表达式,则[操作]将在迭代时完成,并节省内存。

No you wouldn’t alter the “content” of the list, if you could mutate strings that way. But in Python they are not mutable. Any string operation returns a new string.

If you had a list of objects you knew were mutable, you could do this as long as you don’t change the actual contents of the list.

Thus you will need to do a map of some sort. If you use a generator expression it [the operation] will be done as you iterate and you will save memory.


回答 5

您可以执行以下操作:

a = [1,2,3,4,5]
b = [i**2 for i in a]

这称为列表理解,可以使您更轻松地在列表内部循环。

You can do something like this:

a = [1,2,3,4,5]
b = [i**2 for i in a]

It’s called a list comprehension, to make it easier for you to loop inside a list.


回答 6

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])]

The answer given by Jemshit Iskenderov and Ignacio Vazquez-Abrams is really good. It can be further illustrated with this example: imagine that

a) A list with two vectors is given to you;

b) you would like to traverse the list and reverse the order of each one of the arrays

Let’s say you have

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])

You will get

[array([1, 2, 3, 4]), array([3, 4, 6])]

On the other hand, if you do

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])

The result is

[array([4, 3, 2, 1]), array([6, 4, 3])]

回答 7

从您的问题尚不清楚,确定删除哪些字符串的标准是什么,但是如果您有或可以列出要删除的字符串,则可以执行以下操作:

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’]

It is not clear from your question what the criteria for deciding what strings to remove is, but if you have or can make a list of the strings that you want to remove , you could do the following:

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)

which changes my_strings to [‘a’, ‘c’, ‘e’]


回答 8

简而言之,在迭代相同列表的同时对列表进行修改。

list[:] = ["Modify the list" for each_element in list "Condition Check"]

例:

list[:] = [list.remove(each_element) for each_element in list if each_element in ["data1", "data2"]]

In short, to do modification on the list while iterating the same list.

list[:] = ["Modify the list" for each_element in list "Condition Check"]

example:

list[:] = [list.remove(each_element) for each_element in list if each_element in ["data1", "data2"]]