簡體   English   中英

打印 python 中的字典值和鍵(索引)

[英]Print the dictionary value and key(index) in python

我正在嘗試編寫一個代碼,該代碼從用戶輸入一行,將其拆分並將其提供給名為 counts 的雄偉字典。 一切都很好,直到我們向女王陛下索取一些數據。 我想要格式的數據,以便首先打印單詞並在其旁邊打印重復的次數。 下面是我設法編寫的代碼。

counts = dict()
print('Enter a line of text:')
line = input('')

words = line.split()

print('Words:', words)

print('Counting:')
for word in words:
    counts[word]  = counts.get(word,0) + 1
for wording in counts:
    print('trying',counts[wording], '' )

當它執行時,它的 output 是不可原諒的。

Words: ['You', 'will', 'always', 'only', 'get', 'an', 'indent', 'error', 'if', 'there', 'is', 'actually', 'an', 'indent', 'error.', 'Double', 'check', 'that', 'your', 'final', 'line', 'is', 'indented', 'the', 'same', 'was', 'as', 'the', 'other', 'lines', '--', 'either', 'with', 'spaces', 'or', 'with', 'tabs.', 'Most', 'likely,', 'some', 'of', 'the', 'lines', 'had', 'spaces', '(or', 'tabs)', 'and', 'the', 'other', 'line', 'had', 'tabs', '(or', 'spaces).']
Counting:
trying 1 
trying 1 
trying 1 
trying 1 
trying 1 
trying 2 
trying 2 
trying 1 
trying 1 
trying 1 
trying 2 
trying 1 
trying 1 
trying 1 
trying 1 
trying 1 
trying 1 
trying 1 
trying 2 

它只是打印嘗試和重復的次數並且沒有單詞(我認為它在字典中被稱為索引,如果我錯了,請糾正我)

Thankyou

請幫助我,在回答這個問題時請記住我是一個新手,無論是 python 還是堆棧溢出。

您的代碼中沒有任何地方嘗試打印該單詞。 您期望它如何出現在 output 中? 如果你想要這個詞,把它放在要打印的東西列表中:

print(wording, counts[wording])

如需了解更多信息,請查看 package collections並使用Counter構造。

counts = Counter(words)

將為您完成所有字數統計。

您應該使用counts.items()來迭代counts的鍵和值,如下所示:

counts = dict()
print('Enter a line of text:')
line = input('')

words = line.split()

print('Words:', words)

print('Counting:')
for word in words:
    counts[word]  = counts.get(word,0) + 1
for word, count in counts.items(): # notice this!
    print(f'trying {word} {count}')

另請注意,您可以在打印時使用 f 字符串。

我很困惑你為什么trying打印 try 。 試試這個。

counts = dict()
print('Enter a line of text:')
line = input('')

words = line.split()

print('Words:', words)

print('Counting:')
for word in words:
    counts[word]  = counts.get(word,0) + 1
for wording in counts:
    print(wording,counts[wording], '' )

您擁有的代碼迭代字典鍵並僅打印字典中的計數。 你會想做這樣的事情:

for word, count in counts.items():
    print('trying', word, count)

您可能還想使用

from collections defaultdict
counts = defaultdict(lambda: 0)

因此,在添加到字典時,代碼就像

counts[word] += 1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM