Slicing out a specific from a list

↘锁芯ラ 提交于 2020-11-29 19:27:46

问题


I have one list and I want to print out all elements of it but skip one specific.

a = [1,2,3,4,5,6,7,8,9]

I want to print out:

1,3,4,5,6,7,8,9 

(in a column like a regular for-loop)

Is this possible?


回答1:


  1. If you specify the element to be skipped by its position (index):

    for position, element in enumerate(a):
        if position != specified_position:
            print(element)
    
  2. If you specify the element to be skipped by its value:

    for element in a:
        if element != specified_value:
            print(element)
    



回答2:


Just slice on both sides and concatenate:

def skip_over(lst, i):
    return lst[:i] + lst[i + 1:]

skip_over([1, 2, 3, 4, 5], 1) # [1, 3, 4, 5]

If you want to skip over all occurrences of a value, filter with a list comprehension:

def skip_all(lst, v):
    return [x for x in lst if x != v]

skip_all([1, 2, 3, 2, 4, 5], 2) # [1, 3, 4, 5]

If you want to skip over the first occurrence of a value, then use index to get its index:

def skip_first(lst, v):
    try:
        i = lst.index(v)
    except ValueError:
        # value not in list so return whole thing
        return lst
    return lst[:i] + lst[i + 1:]

skip_first([1, 2, 3, 2, 4, 5], 2) # [1, 3, 2, 4, 5]


来源:https://stackoverflow.com/questions/64834210/slicing-out-a-specific-from-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!