繁体   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