为什么我不能将字符串中的空格拆分为空格后进行比较


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.isdigit() and int(i) > 5)
因为这应该会导致语法错误。

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

在这种情况下,我怀疑这是由于数组中的索引在迭代时发生了偏移,同时从中删除了元素。通常不建议在对列表进行迭代时以索引移动的方式修改列表。就像本例中一样,您试图删除空格和特定数字。这意味着在去除";5〃;从数组中,您将得到两个"数组中的str空格。但迭代器不会重置它的计数器。它只执行在进程一开始就确定的一些迭代器。因此不会重置到以前的位置。但与此同时,我们被留下了一个"我们的"quot;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

这是一个更安全的选择,并且如果在迭代原始数组时准备了新数组,则总体上会使整个过程不那么复杂。

我希望它能有所帮助。

尝试像一样编写此代码

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

像这样,空间将像字符串一样评估

filterlist一起使用。还要注意的是,您不应该将str用作变量或函数,因为它在Python中已经是一个符号/函数,它可能会导致一些奇怪的错误。

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']

希望有帮助:(

最新更新