我有一些非常低效的代码,我想让它更通用/更高效。我正在尝试从一组列表中创建字符串。
这是我目前拥有的:
#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']