我怎么去:
{' electronic equipment, petroleum, natural gas, wood, wood products, palm oil, rubber, textiles, chemicals'}
至
{'electronic equipment', 'petroleum', 'natural gas', 'wood', 'wood products', 'palm oil', 'rubber', 'textiles', 'chemicals'}
我怎么去:
{' electronic equipment, petroleum, natural gas, wood, wood products, palm oil, rubber, textiles, chemicals'}
至
{'electronic equipment', 'petroleum', 'natural gas', 'wood', 'wood products', 'palm oil', 'rubber', 'textiles', 'chemicals'}
第一项是set
由单个字符串而不是字典组成。你可以像这样清理它:
s = {' electronic equipment, petroleum, natural gas, wood, wood products, palm oil, rubber, textiles, chemicals'}
s = set( x.strip() for x in s.pop().split(',') )
结果将是另一个set
具有多个字符串成员的:
{'rubber', 'natural gas', 'petroleum', 'electronic equipment', 'wood products', 'chemicals', 'wood', 'palm oil', 'textiles'}
那不是字典,是集合。可能你应该使用一个字符串:
In [16]: strs=' electronic equipment, petroleum, natural gas, wood, wood products, palm oil, rubber, textiles, chemicals'
In [17]: strs.split(",")
Out[17]:
[' electronic equipment',
' petroleum',
' natural gas',
' wood',
' wood products',
' palm oil',
' rubber',
' textiles',
' chemicals']
或者如果你只想在那个集合上工作,那么试试这样的东西。但是您可能无法通过这种方式获得订购的商品:
In [25]: s={' electronic equipment, petroleum, natural gas, wood, wood products, palm oil, rubber, textiles, chemicals'}
In [26]: {y for x in s for y in x.split(",")}
Out[26]:
set([' natural gas',
' chemicals',
' petroleum',
' rubber',
' wood',
' wood products',
' palm oil',
' electronic equipment',
' textiles'])
或@Jon Clements 建议您可以尝试以下操作:
In [43]: next(iter(s)).split(",")
Out[43]:
[' electronic equipment',
' petroleum',
' natural gas',
' wood',
' wood products',
' palm oil',
' rubber',
' textiles',
' chemicals']
你可以试试这个:
>>> s = {'hello,world'}
>>> set(s.pop().split(','))
set(['world', 'hello'])
但是您可能已经注意到它不会被排序(不能保证顺序)。