首页 > 解决方案 > 如何将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

解决方案


您可以依靠 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. 

推荐阅读