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

时间:2012-01-14 22:29:28

标签: python for-loop elements

我对如何在Java中执行此操作有一般的想法,但我正在学习Python并且不确定如何执行此操作。

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

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

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

    print b

15 个答案:

答案 0 :(得分:54)

def altElement(a):
    return a[::2]

答案 1 :(得分:52)

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

return a[::2]

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

答案 2 :(得分:13)

或者,您可以这样做:

for i in range(0, len(a), 2):
    #do something

扩展切片表示法 更加简洁。

答案 3 :(得分:3)

b = a[::2]

这使用extended slice syntax

答案 4 :(得分:3)

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

答案 5 :(得分:3)

  

除了一只皮肤猫之外,还有很多方法。 - Seba Smith

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]

答案 6 :(得分:1)

或者您可以这样做!

    def skip_elements(elements):
        # Initialize variables
        new_list = []
        i = 0

        # Iterate through the list
        for words in elements:

            # Does this element belong in the resulting list?
            if i <= len(elements):
                # Add this element to the resulting list
                new_list.append(elements[i])
            # Increment i
                i += 2

        return new_list

    print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g']
    print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be ['Orange', 'Strawberry', 'Peach']
    print(skip_elements([])) # Should be []

答案 7 :(得分:1)

def skip_elements(elements):
   new_list = [ ]
   i = 0
   for element in elements:
       if i%2==0:
         c=elements[i]
         new_list.append(c)
       i+=1
  return new_list

答案 8 :(得分:1)

# Initialize variables
new_list = []
i = 0
# Iterate through the list
for i in range(len(elements)):
    # Does this element belong in the resulting list?
    if i%2==0:
        # Add this element to the resulting list
        new_list.append(elements[i])
    # Increment i
    i +=2

return new_list

答案 9 :(得分:0)

像你一样使用for-loop,一种方法就是:

def altElement(a):
    b = []
    j = False
    for i in a:
        j = not j
        if j:
            b.append(i)

    print b

j只是在0和1之间切换,以跟踪何时将元素附加到b。

答案 10 :(得分:0)

def skip_elements(elements):
  new_list = []
  for index,element in enumerate(elements):
    if index == 0:
      new_list.append(element)
    elif (index % 2) == 0: 
      new_list.append(element)
  return new_list

也可以用于循环+枚举。 elif(index%2)== 0:##检查数字是否为偶数,不是奇数,原因是索引从零而不是1开始。

答案 11 :(得分:0)

def skip_elements(elements):
    # Initialize variables
    i = 0
    new_list=elements[::2]
    return new_list

# Should be ['a', 'c', 'e', 'g']:    
print(skip_elements(["a", "b", "c", "d", "e", "f", "g"]))
# Should be ['Orange', 'Strawberry', 'Peach']:
print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) 
# Should be []:
print(skip_elements([]))

答案 12 :(得分:0)

return new SendRemainder(configuration.GetValue<string>("AppURL"), hostContext.HostingEnvironment.ContentRootPath, 
                                             configuration.GetValue<string>("SMTPHost"), configuration.GetValue<string>("From"), logger);

答案 13 :(得分:-1)

def skip_elements(elements):
    # code goes here
    new_list=[]
    for index,alpha in enumerate(elements):
        if index%2==0:
            new_list.append(alpha)
    return new_list


print(skip_elements(["a", "b", "c", "d", "e", "f", "g"]))  
print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach']))  

答案 14 :(得分:-2)

def skip_elements(elements):
# Initialize variables
new_list = []
i = 0

# Iterate through the list
for i in range(0,len(elements),2):
    # Does this element belong in the resulting list?
    if len(elements) > 0:
        # Add this element to the resulting list
        new_list.append(elements[i])        
return new_list

print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g']
print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be ['Orange', 'Strawberry', 'Peach']
print(skip_elements([])) # Should be []