提问人:trevnethers 提问时间:4/11/2023 最后编辑:trevnethers 更新时间:4/12/2023 访问量:54
PYTHON 不带括号的分类和打印
PYTHON Sort and Print Dicitonary without Brackets
问:
这是我的代码:
`tv_dict = {}
user_input = input()
file_open = open(user_input)
file_content = file_open.readlines()
new_content = []
for x in file_content:
new_content.append(x.strip())
list_len = len(new_content) // 2
loop_cy = 1
k = -1
v = -2
while loop_cy <= list_len:
key = new_content[k]
value = new_content[v]
tv_dict[key] = value
k += 2
v += 2
loop_cy += 1
val_sort1 = {k:[v for v in tv_dict.keys() if tv_dict[v] == k] for k in set(tv_dict.values())}
val_sort2 = dict(sorted(val_sort1.items(), key=lambda val:val[0]))
file_1a = ''.join("{}: {}\n".format(k, v) for k, v in val_sort2.items())
print(file_1a)`
我正在尝试打印:
10: Will & Grace
12: Murder, She Wrote
14: Dallas
20: Gunsmoke, Law & Order
30: The Simpsons
但我得到:
10: ['Will & Grace']
12: ['Murder, She Wrote']
14: ['Dallas']
20: ['Gunsmoke', 'Law & Order']
30: ['The Simpsons']
注意:如果字典键具有相同的值,则必须一起输出。(如《硝烟》和《法律与秩序》所示)
我可以得到:
10: Will & Grace
12: Murder, She Wrote
14: Dallas
20: Gunsmoke
20: Law & Order
30: The Simpsons
但是按值排序会带回括号和引号。
答:
0赞
jprebys
4/11/2023
#1
您只需要用逗号将列表的值连接在一起即可。试试这样的方法:
file_1a = ''.join("{}: {}\n".format(k, ", ".join(v)) for k, v in val_sort2.items())
print(file_1a)`
0赞
Alain T.
4/12/2023
#2
使用 join 方法用逗号分隔列表项。
D = { 10: ['Will & Grace'],
12: ['Murder, She Wrote'],
14: ['Dallas'],
20: ['Gunsmoke', 'Law & Order'],
30: ['The Simpsons'] }
for key in sorted(D):
print(f"{key}:",", ".join(D[key]))
10: Will & Grace
12: Murder, She Wrote
14: Dallas
20: Gunsmoke, Law & Order
30: The Simpsons
如果需要将所有内容都放在一个字符串中,可以使用联接将行与换行符分隔符 (“\n”) 组合在一起:
file_1a = "\n".join(f"{key}: "+", ".join(D[key]) for key in sorted(D))
评论
file_1a = ''.join("{}: {}\n".format(k, ', '.join(v)) for k, v in val_sort2.items())
?顺便说一句,如果你对输出的唯一问题是 ing,请在最后一步之前只将其与数据样本一起包含在问题中。除了文字定义和最后 2 行之外,在第一个代码块中不需要所有内容来演示问题。print
val_sort2