删除列表中的每个其他元素

huangapple go评论73阅读模式
英文:

Delete every other element from a list

问题

我需要获取一个数组并从数组中删除每个第二个元素。始终保留第一个元素,并从下一个元素开始删除。

示例:

["Keep", "Remove", "Keep", "Remove", "Keep", ...] --> ["Keep", "Keep", "Keep"]

所有这些数组都不会为空。

我发现要删除的元素必须具有奇数索引,尝试使用for循环和取余来解决这个问题:

def remove_every_other(my_list):
    for element in my_list:
        if my_list.index(element) % 2 != 0:
            my_list.remove(element)
    return my_list

当我使用以下列表运行我的代码时:

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
my_list2 = ["hello", "goodbye", "hello again"]
my_list3 = [[1, 2], [1, 2]]
my_list4 = [["goodbye"], {"Great": "Job"}, ["Goodbye"]]

这是当我运行我的代码并在之后打印列表时的结果:

['hello', 'hello again']
[1, 3, 4, 6, 7, 9, 10]
[[1, 2], [1, 2]]
[['goodbye'], ['Goodbye']]

对我来说奇怪的是,该代码对字符串的列表(my_list2)以及列表的列表(my_list4)有效,但如果列表的列表内部包含整数而不是字符串(my_list3),或者如果它是包含整数而不是字符串的列表(my_list),则不起作用。

Python是否根据列表的内容而不是值本身来处理列表?我觉得这里不应该有关,因为我正在检查元素的索引而不是其值本身。

我正在使用Python 3

英文:

I need to take an array and remove every second element from the array. Always keep the first element and start removing with the next element.
Example:

["Keep", "Remove", "Keep", "Remove", "Keep", ...] --> ["Keep", "Keep", "Keep"]

None of the arrays will be empty.

I figured that the element to be removed must have an odd index and tried to solve this problem using a for-loop and modulo:

def remove_every_other():
    for element in my_list:
        if my_list.index(element) % 2 != 0:
            my_list.remove(element)
    return my_list

When I run my code with the following lists:

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
my_list2 = ["hello", "goodbye", "hello again"]
my_list3 = [[1, 2], [1, 2]]
my_list4 = [["goodbye"], {"Great": "Job"}, ["Goodbye"]]

These are the results when I run my code and print the lists afterwards:

['hello', 'hello again']
[1, 3, 4, 6, 7, 9, 10]
[[1, 2], [1, 2]]
[['goodbye'], ['Goodbye']]

It seems odd to me that the code works for a list of strings (my_list2) as well as for a list of lists but (my_list4) but not if the list of lists contains integers instead of strings inside the inner lists (my_list3) or if it is a list containing integers instead of strings (my_list).

Does Python treat lists differently depending on their contents? I feel like that should not matter here since I am checking the indexes of the elements and not the values itself.

I'm using Python 3.

答案1

得分: 0

考虑对正在迭代的列表进行变异的副作用。

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]为例,当你到达第一个奇数索引时,你正在修改你继续迭代的确切列表。你的新列表如下所示:

[1, 3, 4, 5, 6, 7, 8, 9, 10]

你已经改变了大小!这意味着所有的索引都不同,for循环会继续到下一个索引。这很难理解

通常,从概念上讲,构建一个新列表,其中包含你想要的值,会更简单,也更不容易出错。也许可以这样做:

英文:

Consider the side effects of mutating the list you are iterating over.

For the example of my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

When you reach your first odd index, you are altering the exact list you continue to iterate over. Your new list looks like this:

[1, 3, 4, 5, 6, 7, 8, 9, 10]

You've changed the size! This means all the indexes are different, and the for loop continues onto the following index. This is hard to reason about.

Often, it's conceptually simpler and less error-prone to build a new list with the values you want. Maybe something like:

def remove_every_other(my_list):
    new_list = []
    # enumerate is a pythonic alternative for doing your my_list.index(element) idea
    for idx, element in enumerate(my_list):
        if idx % 2 == 0:
            new_list.append(element)
    return new_list

答案2

得分: 0

你可以通过删除索引为奇数的值来解决这个问题。

def rem_odd_index_value(my_list):
    result = []
    for i in range(len(my_list)):
        if i % 2 == 0:
            result.append(my_list[i])
    return result

print(rem_odd_index_value(my_list3))
英文:

You can solve this by removing that value whose index is an odd number.

def rem_odd_index_value(my_list):
    result = []
    for i in range(len(my_list)):
        if i%2==0:
            result.append(my_list[i])
    return result

print(rem_odd_index(my_list3))```

</details>



huangapple
  • 本文由 发表于 2023年2月23日 23:20:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75546813.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定