159328404 发表于 2020-9-21 17:35:34

020作业:统计下边这个长字符串中各个字符出现的次数

统计下边这个长字符串中各个字符出现的次数

def search(*params):
    a = list(params)
    b = []
    for each in params:
      if each not in b:
            b.append(each)

    c = {}
    for each in b:
      c = a.count(each)

    print(c)

search(' sdfdsf')


哪里不对呢...{:5_96:}

kylin121380 发表于 2020-9-21 17:45:47

def search(params):

挥舞乾坤 发表于 2020-9-21 18:00:36

def search(string):
    c = {}
    for e in string:
      c.setdefault(e,0)
      c += 1
    return c

print(search(' sdfdsf'))

城中城 发表于 2020-9-21 18:04:02

def search(*params):
    a = []
    for each in params:
      a.append(each)
    b = []
    for each in params:
      if each not in b:
            b.append(each)

    c = {}
    for each in b:
      c = a.count(each)

    print(c)

search(' sdfdsf')

或者这样
def search(params):
    a = []
    for each in params:
      a.append(each)
    b = []
    for each in params:
      if each not in b:
            b.append(each)

    c = {}
    for each in b:
      c = a.count(each)

    print(c)

search(' sdfdsf')

以修改 希望采纳

疾风怪盗 发表于 2020-9-21 19:54:52

*params就是考虑不定长参数,那就需要多一个循环
然后下面计数也要放进这个循环里

def search(*params):
    a = list(params)
    b = []
    c = {}
    for params_temp in a:
      for each in params_temp:
            if each not in b:
                b.append(each)
      for each in b:
            c = params_temp.count(each)
    print(c)

search(' sdfdsf','sdaaa')

wzdr 发表于 2020-9-21 20:02:30

{:10_256:}{:10_256:}{:10_256:}

知我枯荣 发表于 2021-5-29 23:06:29

f = open("string1.txt")
lines = f.read()
result = {x:lines.count(x) for x in lines}
print(result)
f.close()
页: [1]
查看完整版本: 020作业:统计下边这个长字符串中各个字符出现的次数