繁体   English   中英

计算字母在单词中出现的次数,并按以下格式放置它们:

[英]Count the number of times a letter appears in a word and put them in the following format:

我必须创建一个程序,该程序给定一个短语来计算字母在每个单词中出现的次数并以这种方式打印:

输入:

i see it

输出:

[('i', 1), ('s', 1), ('e', 2), ('i', 1), ('t', 1)]

我的代码仅适用于第一个单词。您能帮我吗?

inicialString=str(input())

words=inicialString.split(" ")
def countTheLetters(t):
 for word in words: 
  thingsList=[]
  for x in word:
   n=word.count(x)
   j=x,n
   thingsList.append(j)
  return thingsList

print(countTheLetters(words))

我的输出:

[('i', 1)]

我试图替换返回的ThingsList,但是它仅适用于最后一个单词。

您每次thingsList for word in words:时都使用for word in words:循环,所以您只会得到最后一个单词。

在第一个for语句之前放置thingsList = []

问题是您在检查第一个单词后立即从函数中返回,而是应将当前单词的结果附加到某个最终列表中,并在处理完所有单词后返回它。

inicialString='i see it'
words=inicialString.split(" ")

def countTheLetters(t):
    ret = []
    for word in words: 
        thingsList=[]
        for x in word:
            n=word.count(x)
            j=x,n
            if not j in thingsList:
                thingsList.append(j)
        ret.extend(thingsList)
    return ret

print(countTheLetters(words))

输出:

[('i', 1), ('s', 1), ('e', 2), ('i', 1), ('t', 1)]

问题是您要在“ for word in word”循环中的每个迭代中重置“ thingsList”,并且还仅在进行一次迭代后返回thingsList列表。

inicialString=str(input())

words=inicialString.split(" ")
def countTheLetters(t):
  thingsList=[]
 for word in words: 
  for x in word:
   n=word.count(x)
   j=x,n
   thingsList.append(j)
return thingsList

print(countTheLetters(words))

更新了代码,请立即检查

inicialString=str(input())

words=inicialString.split(" ")
def countTheLetters(t):
 thingsList=[]
 for word in words:
  for x in word:
   n=word.count(x)
   j=x,n
   thingsList.append(j)
 return thingsList

print(countTheLetters(words))

暂无
暂无

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

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