我有一个列表 json_data:
> print(json_data)
> ['abc', 'bcd/chg', 'sdf', 'bvd', 'wer/ewe', 'sbc & osc']
我需要将那些带有“/”、“&”或“and”的元素拆分成两个不同的元素。我正在寻找的结果应该是这样的:
>['abc', 'bcd', 'chg', 'sdf', 'bvd', 'wer', 'ewe', 'sbc' , 'osc']
代码是:
separators = ['/', 'and', '&']
titles = []
for i in json_data:
titles.extend([t.strip() for t in i.split(separators)
if i.strip() != ''])
运行时出现错误:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-15-d0db85078f05> in <module>()
5 titles = []
6 for i in json_data:
----> 7 titles.extend([t.strip() for t in i.split(separators)
8 if i.strip() != ''])
TypeError: Can't convert 'list' object to str implicitly
如何解决这个问题?
请您参考如下方法:
我相信您在列表理解中寻找的是
[t.strip() for separator in separators for t in i.split(separator) if i.strip() != '']
Python 没有通过分隔符列表自动分隔。
