找到元素索引的字符串中出现的次数

时间:2014-03-25 01:53:44

标签: python

Char_Record是3个项目列表[char, total, pos_list]其中

  • char是一个字符串
  • total是表示char
  • 出现次数的Nat
  • pos_list是代表char
  • 指数的Nat列表

使用函数build_char_records()应生成一个排序列表,其中包含每个字符(小写)。

例如:

>>>build_char_records('Hi there bye')
['',2,[2,8]]
['b',1,[9]]
['e',3,[5,7,11]]
['h',2[0,4]]
['i',1,[1]]
['r',1,[6]]
['t',1,[3]]
['y',1,[10]]

我只是这样写的,我不知道怎么做,有人请帮忙。感谢。

def build_char_records(s):
    s=sorted(s)
    a=[]
    for i in range(len(s)):

3 个答案:

答案 0 :(得分:2)

我认为到目前为止给出的其他答案是从整体编程角度来看更好的答案,但根据您的问题,我认为这个答案适合您的技能水平

def build_char_records(phrase):
    phrase = phrase.lower()
    resultList = []
    for character in phrase: ## iterates through the phrase
        if character not in resultList:
            resultList.append(character) ## This adds each character to the list
                                         ## if it is not already in the list        
    resultList.sort() ## sorts the list
    for i in range(len(resultList)): ## goes through each unique character
        character = resultList[i] ## the character in question
        tphrase = phrase ## a copy of the phrase
        num = phrase.count(character) ## the number of occurences
        acc = 0 ## an accumulator to keep track of how many we've found
        locs = [] ## list of the locations

        while acc < num: ## while the number we've found is less than how many
                         ## there should be
            index = tphrase.find(character) ## finds the first occurance of the character
            tphrase = tphrase[index+1:] ## chops off everything up to and including the
                                        ## character
            if len(locs) != 0: ## if there is more than one character
                index = locs[acc-1] + index + 1 ## adjusts because we're cutting up the string
            locs.append(index)## adds the index to the list
            acc += 1 ## increases the accumulator

        resultList[i] = [character, num, locs] ## creates the result in the proper spot

    return resultList ## returns the list of lists

print build_char_records('Hi there bye')

这将打印出[[' ', 2, [2, 8]], ['b', 1, [9]], ['e', 3, [5, 7, 11]], ['h', 2, [0, 4]], ['i', 1, [1]], ['r', 1, [6]], ['t', 1, [3]], ['y', 1, [10]]]

这是一个稍短,更清洁的版本

def build_char_records(phrase):
    phrase = phrase.lower()
    resultList = []
    for character in phrase: 
        if character not in resultList:
            resultList.append(character) 

    resultList.sort() 
    for i in range(len(resultList)): 
        tphrase = phrase 
        num = phrase.count(resultList[i]) 
        locs = [] 

        for j in range(num):
            index = tphrase.find(resultList[i]) 
            tphrase = tphrase[index+1:]
            if len(locs) != 0:
                index = locs[acc-1] + index + 1
            locs.append(index)

        resultList[i] = [resultList[i], num, locs] 

    return resultList

print build_char_records('Hi there bye')

答案 1 :(得分:0)

from collections import defaultdict

def build_char_records(s):
    cnt = defaultdict(int)
    positions = defaultdict(list)
    for i,c in  enumerate(s):
        cnt[c] += 1
        positions[c].append(i)
    return [  [c, cnt[c], positions[c]] for c in cnt.keys()  ]

答案 2 :(得分:0)

仅使用list,您可以这样做:

def build_char_records(s):
    records = []  # Create a list to act as a dictionary
    for idx, char in enumerate(s):
        char = char.lower()
        current_record = None  # Try to find the record in our list of records
        for record in records:  # Iterate over the records
            if record[0] == char:  # We find it!
                current_record = record  # This is the record for current char
                break  # Stop the search
        if current_record is None:  # This means the list does not contain the record for this char yet
            current_record = [char, 0, []]  # Create the record
            records.append(current_record)  # Put the record into the list of records
        current_record[1] += 1  # Increase the count by one
        current_record[2].append(idx)  # Append the position of the character into the list

    for value in records:  # Iterate over the Char_Record
        print value # Print the Char_Record

或者,如果你需要对它进行排序,你可以做@Dannnno所说的,或者作为一个例子,它可以用这种方式排序(虽然你可能没有学过lambda):

records.sort(key=lambda x: x[0])

在打印记录之前先把它放好。

或者,您可以使用dictlist

来实现
def build_char_records(s):
    record = {}  # Create an empty dictionary
    for idx, char in enumerate(s):  # Iterate over the characters of string with the position specified
        char = char.lower()  # Convert the character into lowercase
        if char not in record:  # If we have not seen the character before, create the Char_Record
            record[char] = [char,0,[]]  # Create a Char_Record and put it in the dictionary
        record[char][1] += 1  # Increase the count by one
        record[char][2].append(idx)  # Append the position of the character into the list
    for value in record.values():  # Iterate over the Char_Record
        print value  # Print the Char_Record