Python 字符串、列表和进程字符串在 for 循环中



我强迫自己正确地学习Python,而不是在我想要什么的时候就去破解它。 浏览一本书,我想在一个 for 循环中处理,这是一个列表:

magicians = ['merlin', 'raistlin', 'gilgamesh', 'gandolf', 'sauron']
for mage in magicians:
#print(mage)
#print(mage.title() + ", is now a master and a planwalker")
s = mage.find("merlin")
print(s)
print("script has Finished...")

找不到,在 for 循环中处理字符串时搜索字符串的方法。 所以我可以搞砸它。(也许我:)很慢(

查找列表中正在处理的项目以便我可以对每个项目执行不同操作的好方法是什么?

您应该使用 if 语句,如下所示:

magicians = ['merlin', 'raistlin', 'gilgamesh', 'gandolf', 'sauron']
for mage in magicians:
#print(mage)
#print(mage.title() + ", is now a master and a planwalker")
if mage =="merlin":
print(mage)
print("script has Finished...")

索引列表。 喜欢..

magicians = ['merlin', 'raistlin', 'gilgamesh', 'gandolf', 'sauron']
length = len(magicians) 
for i in range(length): 
#print(mage)
#print(mage.title() + ", is now a master and a planwalker")
if mage[i] == 'merlin':
print(mage)
print("script has Finished...")

如果你想搜索某些字符,你可以这样做:

magicians = ['merlin', 'raistlin', 'gilgamesh', 'gandolf', 'sauron']
for mage in magicians:
#print(mage)
#print(mage.title() + ", is now a master and a planwalker")
if"mer" in mage :
print(mage)
print("script has Finished...")

您可以使用enumerate打印索引:

magicians = ['merlin', 'raistlin', 'gilgamesh', 'gandolf', 'sauron']
for index, mage in enumerate(magicians):
#print(mage)
#print(mage.title() + ", is now a master and a planwalker")
if mage == "merlin":
print(mage, 'Index of it is', index)
print("Done.")

你可以试试这个:

for mage in magicians:
if mage=="....":
<do whatever you want to do with mage>

通过跟踪列表的索引,我们可以找到正在处理的项目

最新更新