Python 打印排序的dict(元组),每个条目都有新行
我使用操作员import itemgetter的import sys按频率对这个dict进行排序:Python 打印排序的dict(元组),每个条目都有新行,python,sorting,dictionary,printing,Python,Sorting,Dictionary,Printing,我使用操作员import itemgetter的import sys按频率对这个dict进行排序: dictionarydata = {('to', 4648), ('a', 4667), ('and', 6407), ('of', 6703)} 当我打印(dictionarydata)时,我希望输出如下: to : 4648 a : 4667 and : 6407 of : 6703 我所做的一切都不起作用。因为exymple正则表达式似乎不适用于元组;e、 g import re w
dictionarydata = {('to', 4648), ('a', 4667), ('and', 6407), ('of', 6703)}
当我打印(dictionarydata)
时,我希望输出如下:
to : 4648
a : 4667
and : 6407
of : 6703
我所做的一切都不起作用。因为exymple正则表达式似乎不适用于元组;e、 g
import re
with open(dictionarydata) as f:
for line in f:
for word in re.findall(r'\w+', line):
print(word)
这将提供以下输出:
a : 1
b : 2
c : 3
这也与执行以下操作相同:
for x in items:
print(x[0], ":", x[1])
例如。如果您有一组元组,则:
x = {('to', 4648), ('a', 4667), ('and', 6407), ('of', 6703)}
使用\n
将其格式化以连接行,并使用str.format
创建所需行:
print("\n".join(["{} : {}".format(*l) for l in x]))
结果:
to : 4648
a : 4667
and : 6407
of : 6703
请注意,因为您的输入是一个
集合
,所以不能保证顺序。如果它是一个列表
或一个元组
“我试过的都不管用”。至少向我们展示一件您尝试过的事情,我们将从那里开始。如果x
是元组列表,请尝试以下操作:print(“\n”.join([{}:{}.format(*l)表示x中的l])
to : 4648
a : 4667
and : 6407
of : 6703