繁体   English   中英

通过具有不同可能字符的字符串进行迭代

[英]Iterating through a string with different possible characters

我刚刚在这里报名,因为我正在参加Python的在线课程并且一直在使用这个网站来帮助我完成课程。 我是; 卡住了。

我没有发布我的实际作业,而只是我的代码的一个元素我很难与...

我试图使用包含字母表中字母的列表迭代字符串。 我想让列表中的每个字母迭代不同索引处的单词。 例如:

word =“panda”char_list = ['a','b','c']等...输出应该是aanda,panda,paada ......其次是banda,pbnda,pabda,...

我的代码只使用列表中的第一个字符迭代单词。 对不起,我对编码总体来说太新了......

index = 0
word = "panda"
possible_char = ['a', 'b', 'c', 'd', 'o']
for char in possible_char:
    while index < len(word):
        new_word = word[:index] + char + word[index + 1:]
        print (new_word)
        index = index + 1

你非常接近。 您只需将索引重置为零。 所以在for循环之后你的第一个命令应该是index=0

你的while循环只适用于外部for循环的第一次迭代,因为index不会被重置并在第一次完成后保持在len(word) 尝试将初始化的行移动到外部循环内的0

for char in possible_chars:
    index = 0
    while index < len(word):
        #...
index = 0
word = "panda"
possible_char = ['a', 'b', 'c', 'd', 'o']
for char in possible_char:
    index = 0
    while index < len(word):
        new_word = word[:index] + char + word[index + 1:]
        print (new_word)
        index = index + 1

你必须在forloop上重新初始化索引,只是为了重新开始这个词

在完成对每个char的迭代后,您只需将索引重置为0。

index = 0
word = "panda"
possible_char = ['a', 'b', 'c', 'd', 'o']
for char in possible_char:
   index=0
   while index < len(word):
      new_word = word[:index] + char + word[index + 1:]
      print (new_word)
      index = index + 1

你忘了在for循环中初始化索引计数器:

index = 0
word = "panda"
possible_char = ['a', 'b', 'c', 'd', 'o']
for char in possible_char:
    index = 0
    while index < len(word):
        new_word = word[:index] + char + word[index + 1:]
        print (new_word)
        index = index + 1

暂无
暂无

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

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