尝试学习Python。我在字典中有一个键,它的值是一个列表。是否可以将字符串附加到列表中的所有项?
value = {
"mything": ["pizza", "burger", "tacos"]
}
category = "food-"
print (value["mything"])
# prints ['pizza', 'burger', 'tacos']
我想要实现的是这样的输出:
print (value["mything"])
# prints ['food-pizza', 'food-burger', 'food-tacos']
由于您是新手,这里有一个简单的循环来获取您需要的内容。
for key in iter(value.keys()):
value[key] = ["food-"+ v for v in value[key]]
但是,我更喜欢这样:
value['mything'] = ['food-'+v for v in value['mything']]
这是一种简单的方法,部分基于您的代码:
value = {
"mything": ["pizza", "burger", "tacos"]
}
category = "food-"
results = []
for item in value["mything"]:
results.append(category + item)
print(results)
输出:
$ python3 example.py
['food-pizza', 'food-burger', 'food-tacos']
print(["food-"+i for i in value["mything"]])
可以使用列表推导式将类别附加到列表中的所有项
print ([category+food for food in value["mything"]])