gpt4 book ai didi

python - 遍历列表中的字符串

转载 作者:太空宇宙 更新时间:2023-11-04 07:36:30 25 4
gpt4 key购买 nike

<分区>

如何遍历列表中的字符串,以便将特定值添加到字典中?例如,对于给定的列表,我想将每个项目的价格设置为字典键,将它们各自的项目设置为值。

给定:

list = ["10.99,cheese pizza", "4.99,vanilla milkshake", "4.99,chocolate milkshake"]

输出(给定一个空字典):

{"10.99": ["cheese pizza"], "4.99": ["vanilla milkshake", "chocolate milkshake"]}

这是我的尝试:

list = ["10.99,cheese pizza", "4.99,vanilla milkshake", "4.99,chocolate milkshake"]

list = str(list)[1:-1].split(",")
listofitems = {}

ctr = 0
while ctr < len(list):
listofitems[list[0]] = str(list[ctr])
print listofitems
ctr = ctr + 1

我的输出是这样的:

{"'10.99": "'10.99"}
{"'10.99": "cheese pizza'"}
{"'10.99": " '4.99"}
{"'10.99": "vanilla milkshake'"}
{"'10.99": " '4.99"}
{"'10.99": "chocolate milkshake'"}

我做错了什么?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com