在第一个之后跳过所有其他元素

sei*_*u10 42 python for-loop elements

我有一般的想法,如何在Java中这样做,但我正在学习Python,不知道如何做到这一点.

我需要实现一个函数,该函数返回一个包含列表中每个其他元素的列表,从第一个元素开始.

到目前为止,我已经并且不确定如何从这里开始,因为我只是在学习Python中的for循环是如何不同的:

def altElement(a):
    b = []
    for i in a:
        b.append(a)

    print b
Run Code Online (Sandbox Code Playgroud)

Muh*_*uri 64

def altElement(a):
    return a[::2]
Run Code Online (Sandbox Code Playgroud)


Dar*_*con 61

切片表示法 a[start_index:end_index:step]

return a[::2]
Run Code Online (Sandbox Code Playgroud)

其中start_index缺省为0end_index默认为len(a).


Joe*_*ett 15

或者,您可以这样做:

for i in range(0, len(a), 2):
    #do something
Run Code Online (Sandbox Code Playgroud)

扩展的片断记法简洁得多,虽然.

  • 这对我很有帮助,但它与扩展切片表示法不同,因为它为您提供一个索引,然后您可以使用该索引访问原始数组,而不是获取“过滤”数组。所以他们确实有不同的用例。 (2认同)

Mr.*_*irl 6

给猫剥皮的方法不止一种。- 塞巴·史密斯

arr = list(range(10)) # Range from 0-9

# List comprehension: Range with conditional
print [arr[index] for index in range(len(arr)) if index % 2 == 0]

# List comprehension: Range with step
print [arr[index] for index in range(0, len(arr), 2)]

# List comprehension: Enumerate with conditional
print [item for index, item in enumerate(arr) if index % 2 == 0]

# List filter: Index in range
print filter(lambda index: index % 2 == 0, range(len(arr)))

# Extended slice
print arr[::2]
Run Code Online (Sandbox Code Playgroud)


jdi*_*jdi 5

items = range(10)
print items
>>> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print items[1::2] # every other item after the second; slight variation
>>> [1, 3, 5, 7, 9]
]
Run Code Online (Sandbox Code Playgroud)