从 python 中的列表列表中删除逗号

remove comma from list of lists in python

我正在学习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']
>>> 

您可以索引每个项目并构建一个 dict

>>> {'name': x[0], 'popularity': x[1], 'price': x[2], 'cuisine': x[3].split(',')}
{'popularity': '83%',
 'cuisine': ['Chinese', 'Thai', 'Japanese'],
 'price': '$$',
 'name': 'Flavour Fusion'}

如果您只想删除逗号,请使用替换:

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'}