5

我有一些非常低效的代码,我想让它更通用/更高效。我正在尝试从一组列表中创建字符串。

这是我目前拥有的:

#contains categories
numind = [('Length',), ('Fungus',)] 

#contains values that pertain to the categories
records = [('Length', 'Long'), ('Length', 'Med'), ('Fungus', 'Yes'), ('Fungus', 'No')] 

#contains every combination of values between the 2 categories. 
#for example, (Long, Yes) = Length=Long & Fungus = Yes.
combinations = [('Long', 'Yes'), ('Long', 'No'), ('Med', 'Yes'), ('Med', 'No')] 

现在我想创建在我的组合列表中包含每个组合的字符串。这是效率低下的部分。我想要这样我就不必硬连线“numind”列表的长度。有任何想法吗?

values = combinations
valuestring = []

if len(numind) == 0:
   pass
elif len(numind) == 1:
   for a in xrange(len(values)):
      valuestring.append(numind[0][0]+values[a][0]) 

elif len(numind) == 2:
   for a in xrange(len(values)):
      valuestring.append(numind[0][0]+values[a][0]+'_'+numind[1][0]+values[a][1]) 

#and so forth until numind is 10+

输出

['LengthLong_FungusYes', 'LengthLong_FungusNo', 'LengthMed_FungusYes', 'LengthMed_FungusNo']
4

4 回答 4

4

我会使用itertools.productwith collections.OrderedDict(后者不是绝对必要的,但意味着您无需考虑即可获得正确的订单):

>>> from collections import OrderedDict
>>> from itertools import product
>>> 
>>> d = OrderedDict()
>>> for k, v in records:
...     d.setdefault(k, []).append(v)
...     
>>> d
OrderedDict([('Length', ['Long', 'Med']), ('Fungus', ['Yes', 'No'])])
>>> ['_'.join(k+v for k,v in zip(d, v)) for v in product(*d.values())]
['LengthLong_FungusYes', 'LengthLong_FungusNo', 'LengthMed_FungusYes', 'LengthMed_FungusNo']

itertools.product自然产生“每个组合”部分(这实际上称为笛卡尔积,而不是组合):

>>> product(["Long", "Med"], ["Yes", "No"])
<itertools.product object at 0x96b0dec>
>>> list(product(["Long", "Med"], ["Yes", "No"]))
[('Long', 'Yes'), ('Long', 'No'), ('Med', 'Yes'), ('Med', 'No')]

这里的优点是,有多少类别或与任何类别关联的值有多少并不重要:只要在 中指定它们records,它就可以工作。

于 2013-08-27T19:19:56.247 回答
0

尝试使用 itertools

s = 'Length%s_Fungus%s'
l1 = ['Long', 'Med']
l2 = ['Yes', 'No']
[s%x for x in itertools.product(l1, l2)]

这产生

['LenLong_FungusYes',
 'LenMed_FungusNo',
 'LenMed_FungusYes',
 'LenLong_FungusNo']
于 2013-08-27T19:22:15.477 回答
0
>>> numind = [('Length',), ('Fungus',)]
>>> combinations = [('Long', 'Yes'), ('Long', 'No'), ('Med', 'Yes'), ('Med', 'No')] 
>>> ['_'.join(numind[i][0] + v for i, v in enumerate(c)) for c in combinations]
['LengthLong_FungusYes', 'LengthLong_FungusNo', 'LengthMed_FungusYes', 'LengthMed_FungusNo']
于 2013-08-27T19:25:51.210 回答
0

你希望它有多通用?

>>> for item in combinations:
    '_'.join(map(''.join, zip(list(itertools.chain(*numind)), item)))


'LengthLong_FungusYes'
'LengthLong_FungusNo'
'LengthMed_FungusYes'
'LengthMed_FungusNo'
于 2013-08-27T19:30:55.867 回答