如何解决为什么打印此第一索引?
在python课程中解决这个问题,并且终生无法弄清为什么它不起作用。我宁愿给我一个错误而不是打印0!
问题为我提供了显示了字符串的变量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
显示的代码返回:
u is first seen in index = 0
解决方法
您要在x
中建立索引吗?在这种情况下,请使用x.index(o)
在o
中搜索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,x.index(y))
输出:
u is first seen in index = 51
,
您实际上是在寻找'u'.index('u')
y.index(o)
应该为x.index(o)
。
您需要迭代吗?如果您保留前两行,然后使用x.index(y)
,则无需使用while
,for
或if
就可以得到相同的结果。
x = 'Poisson geometry plays an important role in noncommutative geometry.'
y = 'u'
print(y,x.index(y))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。