为什么在拆分为 space 后我无法比较字符串中的 space?

why am I not able to compare a space in string after splitting to a space?

def str_to_list(str):
    # Insert your code here
    new = list(str)
    for i in new:
        if i ==  or (i.isdigit() and int(i) > 5):
            new.remove(i)
    return new

我预计会是 ['d', 'o', 'l', 'l', 'a', 'r']

但是我得到了[' ', 'd', 'o', 'l', 'l', 'a', 'r']

试着把这段代码写成

if i == " " or (i.is digit() and int(i)>5)

像这样 space 将像字符串一样求值

filterlist 结合使用。另请注意,您不应将 str 用作变量或函数,因为它已经是 Python 中的 symbol/function,它可能会导致一些奇怪的错误。

def str_to_list(string):
    new = list(string)
    for i in new:
        if i.isdigit() and int(i) > 5:
            new.remove(i)

    # This will remove all whitespaces from your list.
    return list(filter(str.strip, new))

print(str_to_list("6 dollars"))
# Output: ['d', 'o', 'l', 'l', 'a', 'r', 's']

希望对您有所帮助:)

我想是打错了
if i == or (i.isdigit() and int(i) > 5)
因为这会导致语法错误。

所以我猜这是命中注定的?
if i == " " or (i.isdigit() and int(i) > 5)

在那种情况下,我怀疑这是由于在迭代数组并同时从中删除元素时数组中的索引发生了移动。 通常不建议以索引移动的方式修改列表,同时迭代它。 就像在这个例子中,你试图删除空格和特定数字。这意味着从数组中删除“5”后,数组中将有两个“”str 空格。但是迭代器不会重置它的计数器。它只执行在流程一开始就确定的一些迭代器。所以没有重置到以前的位置。但与此同时,我们留下了一个我们的“”“str,它在“6”被删除后在那里结束。它基本上将它的位置转移到“6”之前的位置。虽然在该位置进行了具体检查“ ”已经离开了。 尽力解释了。但是,是的,这被认为是一种不好的做法是有原因的。这真的让事情变得难以理解。好吧,它确实适合我。 相反,我会建议这样的事情:

def str_to_list(x):
    formatted = [i for i in [s for s in list(x) 
                    if not(s.isdigit() and int(s) > 5)]
                    if not i.ispace()]]
    return formatted

或不太简洁,但更容易理解:

def str_to_list(x):
    new_lst = []
    for i in list(x):
        if i.isspace():
            pass
        elif (i.isdigit() and int(i) > 5):
            pass
        else:
            new_lst.append(i)
    return new_lst

如果在迭代原始数组的同时准备好新数组,这是一个更安全的选择,并且总体上使整个事情变得不那么复杂。

希望对您有所帮助。