【问题标题】:I expect same output I want to remove letters from a list我期望相同的输出我想从列表中删除字母
【发布时间】:2022-01-15 16:59:47
【问题描述】:

我希望这些代码的结果相同,但另一个代码有什么问题。

def remove_letters(list):
    x = []
    for i in range(len(list)):
        if type(list[i]) == type(1):
           x.append(list[i])
    print(x)
    return x
y = [1,'b', 'c',2]
remove_letters(y)
Output >> [1,2] 


def remove_letters(list):
    x = list
    for i in range(len(list)):
        if type(list[i]) == type('a'):
           x.remove(list[i])

    print(x)
    return x


y = [1,'b', 'c',2]
remove_letters(y)

output>> 

Traceback (most recent call last):
  File "/Users/genesissales/PycharmProjects/1. Unbuquity [ 1, a, b, 2]/main.py", line 14, in <module>
    remove_letters(y)
  File "/Users/genesissales/PycharmProjects/1. Unbuquity [ 1, a, b, 2]/main.py", line 6, in remove_letters
    if type(list[i]) == type('a'):
IndexError: list index out of range

Process finished with exit code 1

它给出了一个错误。似乎该列表也正在被 for 循环。

【问题讨论】:

  • 在迭代列表时从列表中删除应该谨慎!

标签: python-3.x list


【解决方案1】:

我对代码进行了编辑,使其更具可读性和 Python 风格。

from copy import copy
# don't use list as variable name, it's a reserved keyword
def remove_letters(l): # actually only keeps integers
    x = []
    for item in l:
        if isinstance(item, int):
           x.append(item)
    print(x)
    return x
y = [1,'b', 'c',2]
remove_letters(y)
#Output >> [1,2]

def remove_letters(l): # does remove all strings
    x = copy(l) # make a copy otherwise the y list from the outer scope is going to be altered! see https://stackoverflow.com/a/47264416/10875953
    for i, item in reversed(list(enumerate(x))): # iterate in reverse order that way it doesn't matter if we delete, enumerate adds the index
        if isinstance(item, str):
            x.remove(i)
    print(x)
    return x


y = [1,'b', 'c',2]
remove_letters(y)

【讨论】:

    猜你喜欢
    • 2020-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-31
    相关资源
    最近更新 更多