我有這個清單:
list1 = ['float', 'x', 'b', 'a', '*', ' ', '=', '50']
和這本詞典:
combined_dict = {
'Keyword': ['float', 'int', 'char'],
'Identifier': ['x', 'b', 'a', 'p', 'n'],
'Operator': ['*', ' ', '=', '-', '/'],
'Constant': ['50', '100', '20']
}
輸出應該是這樣的:
|list | Type |
|:------:|:----------:|
|float | Keyword |
| x | Identifier |
| b | Identifier |
| a | Identifier |
| * | Operator |
| | Operator |
| = | Operator |
| 50 | Constant |
所以這里的目標是在字典的值中找到元素list1并列印相應的鍵。這應該是表格形式,如圖所示。
例如:float來自串列是Keyword字典中的一個鍵。
我真的無法為此設計一個回圈!
uj5u.com熱心網友回復:
你有麻煩,因為你的字典是倒退的。字典用于查找映射到值的鍵,而不是相反。所以首先轉換你的字典:
lookup_dict = {v: k for k, vals in combined_dict.items() for v in vals}
現在任務很簡單:
for s in list1:
print(f'| {s:06s} | {lookup_dict[s]:10s} |')
我想你可以弄清楚如何在表格中列印頁眉和頁腳。
uj5u.com熱心網友回復:
你可以這樣做:
import pandas as pd
combined_dict={'Keyword': ['float','int','char'], 'Identifier': ['x', 'b', 'a','p','n'], 'Operator': ['*', ' ', '=','-','/'], 'Constant': ['50','100','20']}
list1=['float', 'x', 'b', 'a', '*', ' ', '=', '50']
types = []
for fromlistvalue in list1:
for value in combined_dict:
if fromlistvalue in combined_dict[value]:
types.append(value)
df = pd.DataFrame({"list":list1,"Type":types})
uj5u.com熱心網友回復:
很多代碼。對于漂亮的列印,for 回圈可能更具可讀性。
# transform combined_dict, to allow lookup by token from list1
lookup = dict(sum((
[(e, key) for e in value]
for key, value in combined_dict.items()
), []))
# create list with tokens mapped to their corresponding type
mapped = [(key, lookup[key]) for key in list1]
# making it pretty
# column widths for the table based on longest cell in column
width_list = max((len(elem) for elem in list1))
width_type = max((len(t) for _, t in mapped))
# convert mapped tokens into printable rows
converted = ["|{}|{}|".format(
i.ljust(width_list), t.ljust(width_type)) for i, t in mapped]
# prepare header and divider of table
header = "|{}|{}|".format(
"list".ljust(width_list), "type".ljust(width_type))
divider = "| {} | {} |".format(
"-" * (width_list - 2), "-" * (width_type - 2))
# merge all table lines into single string and print
print("\n".join([header, divider] converted))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/417546.html
標籤:
