python - 如何将dict项目转换为句子
问题描述
我有一个带有两个字典索引和注释的输入数据。
indexes={'Laptops':'1','Mob':'2','Cars':'3','Bus':4}
Notes={
'indexs':[1,3],
'Laptops':[
"dell","asus","acer"
],
'Mob':[
"mi","realme"
],
'Bus':[
"aB"
],
'Cars':["Not found"
]
}
创建了一个句子生成器
def SenGen(alpha,beta):
for a,b in alpha.items():
for c,d in beta.items():
if c in a:
print(f"{a} are ", end="")
for i, e in enumerate(b):
if i == len(b)-1:
print(f"and {e}. ", end="")
elif i == len(d)-2:
print(f"{e} ", end="")
else:
print(f"{e}, ", end="")
在 SenGen 的帮助下,我生成了一个如下所示的句子。
SenGen(Notes,indexes)
输出
Laptops are dell, asus, and acer. Mob are mi, and realme. Bus are and aB. Cars are and not found.
在笔记本电脑的上述输出中,我有 3 个单词,由 'and'分隔,**在 mob 中,我有两个单词,由 'and' 分隔 **。而在公共汽车中,我只有一个单词。但是“和”在 aB 的前面,如果是同一 辆车,我还没有找到。
我想要的输出应该如下所示。
输出:
Laptops are dell, asus, and acer. Mob are mi, and realme. Bus are aB. Cars are not found.
我遵循了一系列案例来解决如下所示的问题。
1.if i == len(b)==1:
print(f" is {e} ", end="")
2.if i == len(b)==0:
print(f" is {e} ", end="")
3.if i == len(b)<1:
print(f" is {e} ", end="")
4.if i == len(b)>1:
print(f" is {e} ", end="")
但我无法解决它。
解决方案
您可以依靠 Python 中的列表及其方法来解决您的问题:
keys = list(Notes.keys())
keys.remove('indexs')
for key in keys:
first_clause = ', '.join(Notes[key][:-1])
last_clause = Notes[key][-1:][0]
if len(first_clause) == 0:
print(key + ' is ', last_clause, end='. ')
else:
print(key + ' are ', first_clause, ', and ', last_clause, end='. ')
那么你的输出是:
Laptops are dell, asus , and acer. Mob are mi , and realme. Bus is aB. Cars is Not found.
推荐阅读
- sql - 如何查询gap发现子表周期覆盖了整个父表周期
- javascript - VBA / Internet Explorer:从 OnClick 事件中捕获结果 URL
- mysql - 用 SQL 条目做数学运算
- r - if (start > end) stop("'start' cannot be after 'end'") 出错:尝试执行分钟预测时 R 中需要 TRUE/FALSE 的缺失值
- rstudio - 无法使用、加载或安装 RStudio 包“摘要”
- powerbi - PBI 中逐行的百分位函数
- android - react-native-keyboard-aware-scroll-view中平台之间的不同行为
- windows - windows下使用go 1.13构建dll
- javascript - 如何在 jest 的覆盖范围内忽略 jest 生成的快照?
- excel - Excel 索引/匹配公式问题(列表)