在python中,打印嵌套在字典中而不带括号的列表的最佳方法是什么?

2024-10-01 02:37:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我在自学python,还玩字典。我的目标是从这样一本词典中打印出主谓一致的句子,在列表中没有括号

fav_places={
'Kevin':['Aruba','Montenegro'],
'Bob':['Mexico City','Tiwan'],
'Stan':['Kansas']
}

这就是我想到的

for name, places in fav_places.items():
if len(places)>1:
    print(f"{name}, your favorite places are: {', '.join(places)}.")
else:
    print(f"{name}, your favorite place is {places[0]}")

我把它作为输出

Kevin, your favorite places are: Aruba, Montenegro.
Bob, your favorite places are: Mexico City, Tiwan.
Stan, your favorite place is Kansas

我是否必须将位置列表转换为一个字符串才能在这样的f字符串中使用它?我的目标是否需要使用len函数?最后,在这种情况下,我是否应该使用带有嵌套列表的词典


Tags: namecity目标列表yourarefavorite词典