打印行号和列表长度的Python程序:错误

时间:2018-11-24 05:19:36

标签: python

现在我正在使用while循环来尝试执行此操作,因为我不太擅长使用for循环。如标题所示,我正在尝试打印一张表格,该表格的行号紧挨着每一行的长度。

错误:当我点击运行时,我得到的只是上面的打印输出(行和带破折号的单词数)。我没有得到y和z的一系列打印输出 注意:我可能正在使这种方式变得比其应有的难度

代码:

list1 = ['Lets go outside','pizza time','show me the money']
list2 = []
print('line   number of words')
print('----   ---------------')
x = 0
len_l1 = len(list1)
while len_l1 > 0:
  split_lis1 = list1[0+x].split(' ')
  list2.append(split_lis1)
  len_l1 -= 1
  x += 1
while len_l1 > 0:
  q = 1
  y = len(list1) - len(list1) + q(x)
  z = len(list2[0+x])
  print(y, z)
  len_l1 -= 1
  x += 1

我希望打印出来的样子:

line   number of words
----   ---------------
0        3
1        2
2        4

谢谢。

2 个答案:

答案 0 :(得分:2)

是的,您可能使解决方案过于复杂,因为现成的Python方法可帮助您轻松解决此类问题。对于使用索引的迭代,请使用enumerate,在下面的示例中,我们将索引设置为从1开始。我们还可以使用在fmt中定义的一些简单的字符串格式来确保一致的间距。

li = ['Lets go outside','pizza time','show me the money']

print('line   number of words')
print('----   ---------------')
fmt = ('{}     {}')

for idx, sentence in enumerate(li,1):
    no_of_words = len(sentence.split())
    print(fmt.format(idx, no_of_words))

然后简单地使用split分割空格并获得单词总数,然后让enumerate为您管理整个事情。

>>
line   number of words
----   ---------------
1     3
2     2
3     4

答案 1 :(得分:1)

list1 = ['Lets go outside','pizza time','show me the money']
print('line   number of words')
print('----   ---------------')

for i in range(0, len(list1)):
    length = len(list1[i].split(" "))
    print(i + 1, "        ", length)

查看python文档以获取range and for的详细信息。