我正在学习python。我有一长串包含餐馆数据的清单。每个嵌套列表的格式为[餐馆名称,评级,价格,美食]。
我想填写一个字母,其中的美食映射到餐馆名称,但有些餐厅有多种美食。如何删除逗号?我尝试直接拆分列表,但收到错误信息,并阅读我意识到拆分的文档不是列表方法。然后我尝试首先索引列表然后拆分字符串,但它似乎也没有工作。我错过了什么吗?提前感谢您的建议。
>>> x = ['Flavour Fusion', '83%', '$$', 'Chinese,Thai,Japanese']
尝试1错误
>>> y = x.split(',')
Traceback (most recent call last):
File "<pyshell#54>", line 1, in <module>
y = x.split(',')
AttributeError: 'list' object has no attribute 'split'
>>>
尝试2错误
>>> y = x.split(x[3])
Traceback (most recent call last):
File "<pyshell#55>", line 1, in <module>
y = x.split(x[3])
AttributeError: 'list' object has no attribute 'split'
尝试3,没有错误但不是我想要的:(
>>> y = x[3].split(',')
>>> y
['Chinese', 'Thai', 'Japanese']
>>>
答案 0 :(得分:3)
如果您只想删除逗号,请使用replace:
x = ['Flavour Fusion', '83%', '$$', 'Chinese,Thai,Japanese']
print(x[3].replace(","," "))
'Chinese Thai Japanese'
In [102]: x = ['Flavour Fusion', '83%', '$$', 'Chinese,Thai,Japanese']
In [103]: d = {x[0]: x[3].replace(","," ")}
In [104]: d
Out[104]: {'Flavour Fusion': 'Chinese Thai Japanese'}
答案 1 :(得分:2)
您可以索引每个项目并构建dict
>>> {'name': x[0], 'popularity': x[1], 'price': x[2], 'cuisine': x[3].split(',')}
{'popularity': '83%',
'cuisine': ['Chinese', 'Thai', 'Japanese'],
'price': '$$',
'name': 'Flavour Fusion'}