【问题标题】:index of a letter in string - python 2.7字符串中字母的索引 - python 2.7
【发布时间】:2012-11-27 15:55:51
【问题描述】:

*我正在编辑这个问题,因为我有一些错误,请再读一遍* em>*

我正在构建一个用单词构建字典的函数,例如:

{'b': ['b', 'bi', 'bir', 'birt', 'birth', 'birthd', 'birthda', 'birthday'], 'bi': ['bi', 'bir', 'birt', 'birth', 'birthd', 'birthda', 'birthday'], 'birt': ['birt', 'birth', 'birthd', 'birthda', 'birthday'], 'birthda': ['birthda', 'birthday'], 'birthday': ['birthday'], 'birth': ['birth', 'birthd', 'birthda', 'birthday'], 'birthd': ['birthd', 'birthda', 'birthday'], 'bir': ['bir', 'birt', 'birth', 'birthd', 'birthda', 'birthday']}

这就是它的样子:

def add_prefixs(word, prefix_dict):
lst=[]
for letter in word:
    n=word.index(letter)
    if n==0:
        lst.append(word[0])
    else:
        lst.append(word[0:n])
lst.append(word)
lst.remove(lst[0])
for elem in lst:
    b=lst.index(elem)
    prefix_dict[elem]=lst[b:]
return prefix_dict

它适用于“生日”之类的词,但是当我有一个重复的字母时,我就遇到了问题……例如,“你好”。

{'h': ['h', 'he', 'he', 'hell', 'hello'], 'hell': ['hell', 'hello'], 'hello': ['hello'], 'he': ['he', 'he', 'hell', 'hello']}

我知道是索引的原因(python选择字母第一次出现的索引)但是不知道怎么解决。是的,这是我的作业,我真的很想向你们学习 :)

谢谢!

【问题讨论】:

    标签: python string list function indexing


    【解决方案1】:
    a = 'birthday'
    [a[:i] for i in range(2,len(a)+1)]
    

    给予

    ['bi', 'bir', 'birt', 'birth', 'birthd', 'birthda', 'birthday']
    

    所以你可以用简单的替换你的函数:

    prefix_dict[word] = [word[:i] for i in range(2,len(word)+1)]
    

    【讨论】:

      【解决方案2】:

      使用enumerate:

      for n, letter in enumerate(word):
          if n==0 or n==1:
              continue
          else:
              lst.append(word[0:n])
      

      【讨论】:

      • @ecatmur:我喜欢这个答案的原始形式,它揭示了一个初学者可能不知道的有用功能,但不会为他做功课(也不会做他的为他考虑)。唉,这还不够。 :(
      【解决方案3】:

      假设变量 a 是一个简单的字符串(例如,“birthday”、“hello”),您可以使用:

      for i in range(1,len(a)):
          print a[0:i+1]
      

      【讨论】:

        【解决方案4】:
        def add_prefixs(word, prefix_dict):
            prefix_dict[word] = [ word[:n+1] for n in range(1, len(word)) ]
        

        更好:

        def get_words(word):
            return [ word[:n+1] for n in range(1, len(word)) ]
        prefix_dict[word] = get_words(word)
        

        所以你保持你的功能“纯粹”。

        【讨论】:

        • 仔细看,应该从bi开始,而不是像你的情况从b开始
        • 固定为不包含单个字符
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-25
        • 1970-01-01
        • 2017-10-17
        • 2021-01-21
        • 1970-01-01
        • 2015-04-23
        相关资源
        最近更新 更多