0

我怎么去:

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

3 回答 3

1

第一项是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'}
于 2012-11-18T13:16:33.700 回答
0

那不是字典,是集合。可能你应该使用一个字符串:

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']
于 2012-11-18T12:43:39.647 回答
0

你可以试试这个:

>>> s = {'hello,world'}
>>> set(s.pop().split(','))
set(['world', 'hello'])

但是您可能已经注意到它不会被排序(不能保证顺序)。

于 2012-11-18T12:49:43.930 回答