2016-09-13 36 views
-1
List_of_numbers1to19 = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 
        'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 
        'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 
        'nineteen'] 
List_of_numbers1to9 = List_of_numbers1to19[0:9] 
List_of_numberstens = ['twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy', 
         'eighty', 'ninety'] 

for i in List_of_numbers1to19: 
    print(i) 
list_of_numbers21to99 = [] 
count = 19 
tens_count = 0 
for j in List_of_numberstens: 
    for k in List_of_numbers1to9: 
     if tens_count%10 == 0: 
      #should print an iteration of List_of_numberstens 
      tens_count +=1 
     tens_count +=1 
     print(j, k) 

正如你所看到的,这是越来越乱了:P所以对不起。 基本上我试图用三个不同索引来打印它们。我已经尝试切分列表并将列表编入索引,但我一直获得数字乘以10的输出作为List_of_numberstens的完整列表。从1-100中打印数字作为Python中的单词3

我想这很清楚我在这里要做什么。

在此先感谢您的帮助!

+1

阅读有关'dict's – dawg

+0

看[num2words] (https://pypi.python.org/pypi/num2words) – dawg

+0

:P我知道,我只是想弄清楚如何在for循环中嵌入for循环。 – snuffles101

回答

6

我知道你已经接受一个答案,但你特别提到嵌套循环 - 它不使用 - 和你错过了什么是伟大的关于Python的迭代,而不是需要做那种i//10-2print(j,k)编制索引到列表中的东西。

Python的for循环迭代运行在直接在列表中的项目,你可以直接打印出来,所以我回答:

digits = ['one', 'two', 'three', 'four', 'five', 
      'six', 'seven', 'eight', 'nine'] 

teens = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 
      'sixteen', 'seventeen', 'eighteen', 'nineteen'] 

tens = ['twenty', 'thirty', 'fourty', 'fifty', 
      'sixty', 'seventy', 'eighty', 'ninety'] 

for word in digits + teens: 
    print(word) 

for tens_word in tens: 
    print(tens_word)  # e.g. twenty 

    for digits_word in digits: 
     print(tens_word, digits_word) # e.g. twenty one 

print("one hundred") 

Try it online at repl.it

+0

这是我很好奇的,谢谢,非常清晰和简洁,不像我的问题:P。 – snuffles101

1

我认为你是过度复杂的20-100的情况。从20到100,数字非常规则。 (即它们的格式为<tens_place> <ones_place>)。

通过只使用一个循环而不是嵌套循环使代码更简单。现在我们只需要弄清楚十几个地方是什么,以及那个地方是什么。

通过使用整数除以10可以容易地找到十位。(因为列表以20开始,我们减去2)。

通过使用模运算符10可以类似地找到那些地方。 (因为列表以1开始而不是0开始减1)。

最后,我们通过使用一个if语句(并且不打印任何一个地点值)来分别处理那些地方为0的情况。

List_of_numbers1to19 = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 
         'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 
         'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 
         'nineteen'] 
List_of_numberstens = ['twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy', 
         'eighty', 'ninety'] 

for i in range(19): 
    print(List_of_numbers1to19[i]) 

for i in range(20, 100): 
    if i%10 == 0: #if multiple of ten only print tens place 
    print(List_of_numberstens[i//10-2]) #20/10-2 = 0, 30/10-2 = 1, ... 
    else: #if not, print tens and ones place 
    print(List_of_numberstens[i//10-2] + ' ' + List_of_numbers1to19[i%10-1]) 
+0

真棒谢谢你,你的权利,我倾向于过分复杂的东西.... – snuffles101