为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Cats萌萌 2023-06-20 15:40:39
在 python 课程中解决这个问题,但我终生无法弄清楚为什么这行不通。我宁愿它给我一个错误也不愿打印 0!问题给了我显示的字符串的变量x,需要打印第一次y使用的索引。x = 'Poisson geometry plays an important role in noncommutative geometry.'y = 'u'i = 0while i == 0:    for o in x:        if o == y:            print(y, "is first seen in index = ", y.index(o))            i += 1显示的代码返回:u is first seen in index =  0
查看完整描述

3 回答

?
心有法竹

TA贡献1866条经验 获得超5个赞

你想要索引x吗?在这种情况下,使用x.index(o)where 搜索oin 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

然而,正确的写法是没有循环:


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

y = 'u'


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

输出:


u is first seen in index =  51


查看完整回答
反对 回复 2023-06-20
?
慕桂英546537

TA贡献1848条经验 获得超10个赞

您实际上是在寻找'u'.index('u')

y.index(o)应该是x.index(o)这个例子。


查看完整回答
反对 回复 2023-06-20
?
FFIVE

TA贡献1797条经验 获得超6个赞

你需要迭代吗?如果您保留前 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))


查看完整回答
反对 回复 2023-06-20
  • 3 回答
  • 0 关注
  • 123 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信