Python str从列表中切片

Python str从列表中切片,python,object-slicing,Python,Object Slicing,我将编写一个小函数来检查列表中是否有字符串,如果是,则应将该字符串从列表中删除 这是我的密码 def str_clearer(L): for i in L: if i == str: L.remove(i) else: pass print(L) return L L = [1, 2, 3, "hallo", "4", 3.3] str_clearer(L) assert str_cle

我将编写一个小函数来检查列表中是否有字符串,如果是,则应将该字符串从列表中删除

这是我的密码

def str_clearer(L):
    for i in L:
        if i == str:
            L.remove(i)
        else:
            pass
    print(L)
    return L

L = [1, 2, 3, "hallo", "4", 3.3]

str_clearer(L)

assert str_clearer(L) == [1, 2, 3, 3.3]
但这与列表无关。

如果我让它生成一个包含所有int或float的新列表,他什么也不做。

类型检查可以使用
isinstance
完成。这实际上可以在列表中非常优雅地完成:

result = [x for x in L if not isinstance(x, str)]

可以使用
isinstance
进行类型检查。这实际上可以在列表中非常优雅地完成:

result = [x for x in L if not isinstance(x, str)]
Python内置函数,可以在这里使用

以下方法与您的方法类似

In[0]: def remove_str(your_list):
           new_list = []    
           for element in your_list:
           if not(isinstance(element, str)):
               new_list.append(element)
           return new_list

In[1]: remove_str([1, 2, 3, "hallo", "4", 3.3])
Out[1]: [1, 2, 3, 3.3]
不过,这可能要短得多

In[2]: mylist = [1, 2, 3, "hallo", "4", 3.3]
In[3]: result = [x for x in mylist if not(isinstance(x, str))]
In[4]: print(result)
Out[4]: [1, 2, 3, 3.3]
Python内置函数,可以在这里使用

以下方法与您的方法类似

In[0]: def remove_str(your_list):
           new_list = []    
           for element in your_list:
           if not(isinstance(element, str)):
               new_list.append(element)
           return new_list

In[1]: remove_str([1, 2, 3, "hallo", "4", 3.3])
Out[1]: [1, 2, 3, 3.3]
不过,这可能要短得多

In[2]: mylist = [1, 2, 3, "hallo", "4", 3.3]
In[3]: result = [x for x in mylist if not(isinstance(x, str))]
In[4]: print(result)
Out[4]: [1, 2, 3, 3.3]