跳过第一个元素之后的所有其他元素
我知道如何在 Java 中执行此操作,但我正在学习 Python,并且不确定如何在 Python 中执行此操作。
我需要实现一个函数,该函数返回一个列表,其中包含源列表的所有其他元素(从第一个元素开始)。
到目前为止,我已经有了这个,但我不知道如何从这里开始:
def altElement(a):
b = []
for i in a:
b.append(a)
print b
I have the general idea of how to do this in Java, but I am learning Python and I am not sure how to do it in Python.
I need to implement a function that returns a list containing every other element of the source list, starting with the first element.
Thus far, I have this and I am not sure how to do from here:
def altElement(a):
b = []
for i in a:
b.append(a)
print b
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(15)
切片符号
a[start_index:end_index:step]
,其中
start_index
默认为0
,end_index
默认为>len(a)
。Slice notation
a[start_index:end_index:step]
where
start_index
defaults to0
andend_index
defaults to thelen(a)
.或者,您可以这样做:
不过,扩展切片符号更加简洁。
Alternatively, you could do:
The extended slice notation is much more concise, though.
这使用扩展切片语法。
This uses the extended slice syntax.
或者你也可以这样做!
Or you can do it like this!
使用像您一样的 for 循环,一种方法是:
j 不断在 0 和 1 之间切换,以跟踪何时将元素附加到 b。
Using the for-loop like you have, one way is this:
j just keeps switching between 0 and 1 to keep track of when to append an element to b.
也可以使用for循环+枚举。
elif (index % 2) == 0: ## 检查数字是否为偶数,而不是奇数,因为索引从 0 开始,而不是 1。
Also can use for loop + enumerate.
elif (index % 2) == 0: ## Checking if number is even, not odd cause indexing starts from zero not 1.