为什么这个函数不返回空格的索引

为什么这个函数不返回空格的索引

本文介绍了Python - 为什么这个函数不返回空格的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

此代码将返回数字和非字母数字字符的索引.但是,它只会返回第一个空格的索引,而不会返回任何其他空格的索引,我不确定为什么.

This code will return the index of the numbers and and the non-alphanumeric characters. However, it will only return the index for the first white space but not any of the others and I'm not really sure why.

shoestring = "fwefw1234132 lkjaldskf98:[]['asd fads fadsf"

for n in shoestring:
    if n.isalpha():
        continue
    else:
        print n, shoestring.index(n)

推荐答案

每次,您都在调用 shoestring.index(n).n 只是一个 ' ' 字符.它无法知道您想要第一个空格,还是第二个,还是第 43 个,因此它只会返回第一个空格.

Each time, you're calling shoestring.index(n). That n is just a ' ' character. It has no way of knowing whether you want the first space, or the second, or the 43rd, so it just returns you the first space.

正确的方法是跟踪索引,而不是搜索以找到它.* enumerate 函数使这很容易:

The right way to do this is to keep track of the index, instead of searching to find it.* The enumerate function makes this very easy:

for i, n in enumerate(shoestring):
    if n.isalpha():
        continue
    else:
        print n, i

作为旁注,您可以通过反转 if 使您的代码更简单,因此您不需要 continue:


As a side note, you can make your code a lot simpler by just reversing the if, so you don't need the continue:

for i, n in enumerate(shoestring):
    if not n.isalpha():
        print n, i

您可以使用 filter 函数或理解获得更多乐趣:

You can have even more fun using the filter function or a comprehension:

nonalphas = ((n, i) for i, n in enumerate(shoestring) if not n.isalpha())
print '\n'.join('{} {}'.format(n, i) for n, i in nonalphas)

* 即使您的搜索正确,它也会使您的代码变慢.如果您有一百万个字符的所有空格字符串,则每次搜索必须检查一百万个字符,并且您必须对每个空格执行一次,这意味着进行一万亿次比较.如果您只是随时跟踪索引,则只有一百万次比较.从技术角度来说,它是线性的,而不是二次的.


* Even if you got the search right, it would also make your code a lot slower. If you have a million-character string of all spaces, each search has to check a million characters, and you have to do this once for each space, which means one trillion comparisons. If you just keep track of the index as you go, it's only one million comparisons. In technical terms, it's linear instead of quadratic.

这篇关于Python - 为什么这个函数不返回空格的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 20:53