如何从字典值推断出一个单独的元素?

2024-04-29 15:45:45 发布

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

apartments = dict(living_room = ['sofa', 'coffee table', 'bookshelf', 'armchair'],
                  kitchen = ['stove', 'fridge', 'sink', 'shelves'],
                  bedroom = ['closet', 'bureau', 'bed', 'blinds', 'chest of drawers'],
                  bathroom = ['shower', 'bathtub', 'lavatory pan', 'shower cubicle'])

first_customer = ('I see you have a nice {}, you can sell to me that?'.format(*apartments['kitchen']))

print(first_customer)

我看你有一台漂亮的冰箱,你能卖给我吗


Tags: youtablecustomerdictfirstroomcoffeesofa
1条回答
网友
1楼 · 发布于 2024-04-29 15:45:45

更新

如果我没弄错的话,这个就行了:

first_customer = ['I see you have a nice {}, you can sell to me that?'.format(x) for x in apartments['kitchen']]
print('\n'.join(first_customer))

first_customer应该初始化为一个列表,然后获取for循环(或上面的list comprehension)中的每个值,并将其格式化为字符串

因此,如果要打印kitchen的第二个元素,请执行以下操作:

print(first_customer[1])

相关问题 更多 >