Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.0k views
in Technique[技术] by (71.8m points)

输出商品列表(python题目)

输出商品列表,用户输入序号,显示用户选中的商品

"""

商品列表:

goods = [
{"name": "电脑", "price": 1999},
{"name": "鼠标", "price": 10},
{"name": "游艇", "price": 20},
{"name": "美女", "price": 998}
]

要求:
1:页面显示 序号 + 商品名称 + 商品价格,如:
      1 电脑 1999
      2 鼠标 10
      ...
for i in goods:
    for num in range(1, len(goods) + 1):
        print(str(num)+" "+i.get("name") + " " + str(i.get("price")))
1 电脑 1999
2 电脑 1999
3 电脑 1999
4 电脑 1999
1 鼠标 10
2 鼠标 10
3 鼠标 10
4 鼠标 10
1 游艇 20
2 游艇 20
3 游艇 20
4 游艇 20
1 美女 998
2 美女 998
3 美女 998
4 美女 998

这个结果明显不对。要怎么改呢?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

如此这般即可

for i,v in zip(range(1,len(goods)+1),goods):
    print(i,v['name'],v['price'])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...