【问题标题】:Removing an index element from a list从列表中删除索引元素
【发布时间】:2019-11-15 23:54:44
【问题描述】:

我正在尝试从列表中删除一个元素,但只能使用 range 函数和 append 方法(作业问题)。当索引元素位置不等于位置参数时,我的“for循环”工作正常。但是,我似乎无法让我的 if 语句正常工作到所需的输出。任何帮助将不胜感激。

这是我的代码:

def length(my_list):

    result = 0
    for char in my_list:
        result += 1

    return result

def remove(my_list, position):

    new_list2 = [] # Create a new list
    length2 = length(my_list) # Calls upon the length function

    if position < 0:
        new_list2.append(my_list[position])

    for r in range(length2):
        if r != position:
            new_list2.append(my_list[r])

    if position > length2:
        (my_list)

    return new_list2

str_list5 = ['f','i','r','e']
new_list = remove(str_list5, 2)
print(new_list)
new_list = remove(str_list5, -1)
print(new_list)
new_list = remove(str_list5, 10)
print(new_list)

我在特定位置 -1 和 10 的输出应该是:

['i','r','e']
['f','i','r']

【问题讨论】:

  • 您是否有理由编写自己的length() 函数而不是仅使用内置的len()
  • 您希望(my_list) 做什么?
  • 您能解释一下为什么您期望-110 获得这些结果吗? r != position 将始终为真,因此它将附加所有列表元素。
  • 为什么position = -1 会产生与position = 0 相同的结果?
  • 我说“请编辑问题”。重要细节不应出现在 cmets 中。

标签: python append element


【解决方案1】:

从讨论中,我收集到超出范围的position 值应该删除近端字符。如果是这样,那么您需要正确地执行“剪辑到轨道”逻辑,并且在您执行正常的单字符删除之前:

# A negative position means to remove the first char
if position < 0:
    position = 0
# A large position means to remove the last char
elif position >= length2:
    position = length2 - 1

# With that done, your existing "skip one char" logic should finish the job
for r in range(length2):
    if r != position:
        new_list2.append(my_list[r])

【讨论】:

  • 非常感谢@Prune。我可以看到我哪里出错了。谢谢
【解决方案2】:

你可以写一个这样的函数:

def remove(string, i):
    length = len(string)
    if i > len(string):
        i =  i // length
    elif i < 0:
        i = len(string) - 1
    print([x for index, x in enumerate(string) if index != i])

str_list5 = ['f','i','r','e']   
remove(str_list5, 2)
['f', 'i', 'e']

索引:

remove(str_list5, -1)
['f', 'i', 'r']

这个怎么样?

myturn = ['this was cool']
remove(*myturn, 6)
['t', 'h', 'i', 's', ' ', 'w', 's', ' ', 'c', 'o', 'o', 'l']

【讨论】: