[英]How can I write a python program, which prints out all the substrings which are at least three characters long?
[英]Python program which prints out line number and length of list: Error
現在我正在使用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
謝謝。
是的,您可能會使解決方案過於復雜,因為有開箱即用的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
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文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.