【问题标题】:Python list index not in orderPython列表索引不按顺序
【发布时间】:2022-10-25 00:12:27
【问题描述】:

我正在努力使我的文本像问题一样在大写和小写之间交替出现。它似乎在索引中跳过了 3,我不知道为什么。

sentence = input("Write a sentence")

newList = []
for i in range(len(sentence)):
    if sentence[i] != " ":
        newList.append(sentence[i])


listJoint = "".join(newList)
newList2 = []

for i in range(len(listJoint)):
    if (listJoint.index(listJoint[i]) % 2) == 0:
        print(listJoint.index(listJoint[i]))
        newList2.append(listJoint[i].upper())
    elif (listJoint.index(listJoint[i]) % 2) != 0:
        print(listJoint.index(listJoint[i]))
        newList2.append(listJoint[i].lower())

print(newList2)

#newListJoint = "".join(newList2)
#print(newListJoint[::-1])

提前致谢 List index doesn't go 0 1 2 3 4

【问题讨论】:

  • 请将您的代码作为文本发布。
  • 将代码视为图像使得复制粘贴和测试变得更加困难
  • index 是非常不适合这项工作的工具。请记住,index 返回字符的第一次出现。如果您有 3 个 L,则每次都会返回相同的 L。你需要让你的循环通过索引。
  • 考虑使用列表比较像这样 - ans = [ch.upper() if not idx%2 else ch.lower() for idx, ch in enumerate(word)]

标签: python list indexing


【解决方案1】:

函数 .index() 查找该字母的第一次出现。 'L' 出现在索引 2 和 3 处,因此它会为两个 L 返回 2。

【讨论】:

    【解决方案2】:

    遍历字符串的每个字符并交替使用上/下方法。

    sentence = "Hello"
    
    alternated_sentence = ''
    for i, char in enumerate(sentence):
        if i % 2:
            alternated_sentence += char.upper()
        else:
            alternated_sentence += char.lower()
    
    print(alternated_sentence)
    #hElLo
    

    【讨论】:

      【解决方案3】:
      sentence = input("Write a sentence:")
      # Remove spaces (as per your question)
      sentence = sentence.replace(' ', '')
      # Reverse the string order (as per your question)
      sentence = sentence[::-1]
      
      result = []
      for i in range(len(sentence)):
        if(i%2==1):
          result.append(sentence[i].lower())
        else:
          result.append(sentence[i].upper())
      
      print(''.join(result))
      

      这是解决方案。上面的代码将给出如下输出:

      Write a sentence: Hello world
      DlRoWoLlEh
      

      【讨论】:

        【解决方案4】:

        我从来没有意识到索引方法引用了字符的第一个实例。这有效:

        sentence = input("Write a sentence")
        
        newList = []
        for i in range(len(sentence)):
            if sentence[i] != " ":
                newList.append(sentence[i])
        
        
        listJoint = "".join(newList)
        newList2 = []
        
        
        for i, value in enumerate(newList):
            if i % 2 == 0:
                newList2.append(listJoint[i].upper())
            elif i % 2 !=0:
                newList2.append(listJoint[i].lower())
        
        newListJoint = "".join(newList2)
        print(newListJoint[::-1])
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-09-25
          • 2021-01-07
          • 2017-06-23
          • 1970-01-01
          • 1970-01-01
          • 2011-03-16
          • 1970-01-01
          相关资源
          最近更新 更多