根据列表生成字符串矩阵

时间:2013-05-07 18:03:01

标签: python

我想根据我的数据生成一个矩阵:

[[0,1],[1,0],[0,2],[1,1],[2,0],[0,3],[1,2],[2,1] ],[3,0]]

我想要做的是,如果方括号内的和等于1,则产生一个字符串变量y_n,其中n是满足该条件的列表的计数器, 和yxn如果总和大于1,其中n计算生成的字符串数。 因此,对于我的数据,它应该产生:

y_1 
y_2
yx1
yx2

直到

yx7

所以我最好的尝试是:

if len(gcounter) != 0:
  hg = len(gcounter[0])
else:
  hg=1
  LHS=Matrix(hg,1,lambda i,j:(var('yx%d' %i)))
print(LHS)

数据称为gcounter。

它没有给我一个错误,但它没有填充LHS的任何东西

1 个答案:

答案 0 :(得分:1)

我不完全确定我理解你正在做什么,但我认为这台发电机可以做你想做的事情:

def gen_y_strings(data):
    counter_1 = counter_other = 0
    for item in data:
        if sum(item) == 1:
            counter_1 += 1
            yield "y_{}".format(counter_1)
        else:
            counter_other += 1
            yield "yx{}".format(counter_other)

您可以像这样运行:

for result in gen_y_strings(gcounter):
    print(result)

根据示例数据,输出您想要的内容:

y_1
y_2
yx1
yx2
yx3
yx4
yx5
yx6
yx7