简体   繁体   English

为什么这个打印第一个索引?

[英]Why is this printing first index?

Working on this problem for a python course and can't for the life of me figure out why this doesn't work.为 Python 课程解决这个问题,但我终其一生都无法弄清楚为什么这不起作用。 I'd rather it give me an error than print 0!我宁愿它给我一个错误而不是打印 0!

Problem gives me the variable x with the string shown and need to print the index of the first time y is used.问题给了我显示字符串的变量x并且需要打印第一次使用y的索引。

x = 'Poisson geometry plays an important role in noncommutative geometry.'
y = 'u'

i = 0
while i == 0:
    for o in x:
        if o == y:
            print(y, "is first seen in index = ", y.index(o))
            i += 1

Code shown returns:显示的代码返回:

u is first seen in index =  0

Did you want index in x ?你想要x索引吗? In that case, use x.index(o) where searches for o in x .在这种情况下,使用x.index(o) where 搜索o in x

x = 'Poisson geometry plays an important role in noncommutative geometry.'
y = 'u'

i = 0
while i == 0:
    for o in x:
        if o == y:
            print(y, "is first seen in index = ", x.index(o))
            i += 1

However, the correct way to write it is without the loop:但是,正确的写法是没有循环:

x = 'Poisson geometry plays an important role in noncommutative geometry.'
y = 'u'

print(y, "is first seen in index = ", x.index(y))

output:输出:

u is first seen in index =  51

You're essentially having it look for 'u'.index('u')您实际上是在寻找'u'.index('u')

y.index(o) should be x.index(o) for this example.对于这个例子, y.index(o)应该是x.index(o)

Do you need to iterate?你需要迭代吗? If you keep your first 2 lines then use x.index(y) you will get the same result without using a while , for or if .如果您保留前 2 行,然后使用x.index(y)您将获得相同的结果,而无需使用whileforif

x = 'Poisson geometry plays an important role in noncommutative geometry.'
y = 'u'
print(y, "is first seen in index = ", x.index(y))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM