简体   繁体   English

从 python 中的该数组中删除每隔一个元素

[英]Removing every second element out of that array in python

I am using codewars.com to exercise my learning in python 3. I am new to this language.我正在使用 codewars.com 来锻炼我在 python 3 中的学习。我是这种语言的新手。 This is the exercise that I have to do.这是我必须做的练习。

Take an array and remove every second element out of that array.取出一个数组并从该数组中删除每个第二个元素。 Always keep the first element and start removing with the next element.始终保留第一个元素并从下一个元素开始删除。

And this is an example, to make it clearer:这是一个示例,以使其更清楚:

my_list = ['Keep', 'Remove', 'Keep', 'Remove', 'Keep', ...]

I understand that the elements of an array start counting from zero, I also understand that starting from one, odd numbers start counting.我了解数组的元素从零开始计数,我也了解从一开始,奇数开始计数。 If I delete the items with odd keys, I would be doing the exercise.如果我删除带有奇数键的项目,我会做这个练习。 I have no idea where to start, but this was my attempt:我不知道从哪里开始,但这是我的尝试:

def remove_every_other(my_list):

    for i in my_list:
        if my_list[i] % 2 != 0:
            my_list[i]
    return my_list

any other idea?还有其他想法吗?

You can do slicing:您可以进行切片:

new_list = my_list[::2]

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

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