Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 嵌套循环:计算单词中的字母数_Python_Python 3.x - Fatal编程技术网

Python 嵌套循环:计算单词中的字母数

Python 嵌套循环:计算单词中的字母数,python,python-3.x,Python,Python 3.x,我的一门课有以下问题,但我有点卡住了。我已经创建了下面的代码,但当我打印时,它只打印最后一个单词的计数,而不是每个单词的计数 使用嵌套循环计算nmrls列表中每个元素的字母数,然后打印元素及其字母数 发现问题:)在x上循环两次将覆盖该值 !pip install inflect import inflect nmrls = inflect.engine() x=[] for i in range (0,22): x.append(nmrls.number_to_words(i))

我的一门课有以下问题,但我有点卡住了。我已经创建了下面的代码,但当我打印时,它只打印最后一个单词的计数,而不是每个单词的计数

使用嵌套循环计算
nmrls
列表中每个元素的字母数,然后打印元素及其字母数

发现问题:)在x上循环两次将覆盖该值

!pip install inflect
import inflect


nmrls = inflect.engine()
x=[]
for i in range (0,22):
    x.append(nmrls.number_to_words(i))   
for nmrls in x:
    count=0
    for letter in nmrls:
        count+=1
    print(nmrls, count)

添加单词后,
x
的内容是什么?你在
x
上循环了两次,因此得到的
计数实际上是
x
中的项目数,而不是
nmrls
中的字母数,对于x中的字母:
=>
对于nmrls中的字母:
!pip install inflect
import inflect


nmrls = inflect.engine()
x=[]
for i in range (0,22):
    x.append(nmrls.number_to_words(i))   
for nmrls in x:
    count=0
    for letter in nmrls:
        count+=1
    print(nmrls, count)