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

发布于 2024-12-27 07:12:18 字数 263 浏览 6 评论 0原文

我知道如何在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

丿*梦醉红颜 2025-01-03 07:12:18
def altElement(a):
    return a[::2]
def altElement(a):
    return a[::2]
余厌 2025-01-03 07:12:18

切片符号 a[start_index:end_index:step]

return a[::2]

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

Slice notation a[start_index:end_index:step]

return a[::2]

where start_index defaults to 0 and end_index defaults to the len(a).

只等公子 2025-01-03 07:12:18

或者,您可以这样做:

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

不过,扩展切片符号更加简洁。

Alternatively, you could do:

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

The extended slice notation is much more concise, though.

彼岸花似海 2025-01-03 07:12:18
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]
]
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]
]
黑白记忆 2025-01-03 07:12:18

给猫剥皮的方法不止一种。 - 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]

There are more ways than one to skin a cat. - 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]
聽兲甴掵 2025-01-03 07:12:18
b = a[::2]

这使用扩展切片语法

b = a[::2]

This uses the extended slice syntax.

岛徒 2025-01-03 07:12:18

或者你也可以这样做!

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

Or you can do it like this!

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

梦回旧景 2025-01-03 07:12:18
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
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
伤痕我心 2025-01-03 07:12:18
# 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
# 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
合久必婚 2025-01-03 07:12:18

使用像您一样的 for 循环,一种方法是:

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

    print b

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

Using the for-loop like you have, one way is this:

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

    print b

j just keeps switching between 0 and 1 to keep track of when to append an element to b.

谢绝鈎搭 2025-01-03 07:12:18
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

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

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

Also can use for loop + enumerate.
elif (index % 2) == 0: ## Checking if number is even, not odd cause indexing starts from zero not 1.

月依秋水 2025-01-03 07:12:18
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([]))
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([]))
≈。彩虹 2025-01-03 07:12:18
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.insert(i,elements[i])
        # Increment i
        i += 2

    return new_list
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.insert(i,elements[i])
        # Increment i
        i += 2

    return new_list
纵性 2025-01-03 07:12:18
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']))  
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']))  
丑疤怪 2025-01-03 07:12:18
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 []
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 []
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文