使用嵌套列表索引列表

时间:2018-03-19 12:28:00

标签: python recursion simulation genetic-algorithm nested-lists

我有一个频率列表(即freq_lst),需要通过嵌套列表检索才能进行计算。使用freq_lst和r_freq完成计算,如下所示:

freq_lst = [0.03571429, 0.03571429, 0.07142857, 0.07142857, 0.10714286, 0.07142857, 0.07142857, 0.03571429, 0.07142857, 0.03571429, 0.03571429, 0.03571429, 0.07142857, 0.03571429, 0.03571429, 0.03571429, 0.03571429, 0.03571429, 0.03571429, 0.03571429]

nested_lst = [['R0','F1','F3','F5','F7','F9','F10'],
['R1','F0','F4','F7','F10','F16'],
['R2','F6','F7','F9','F13','F17','F18'],
['R3','F2','F8','F10','F18','F19'],
['R4','F10','F11','F12','F14','F15','F16']]

r_lst = ['R0','R1','R2','R3','R4']
r_freq = [0.1, 0.2, 0.2, 0.2, 0.3]

def mating_func():
    mating = []
    for k in range(len(r_lst)):
        for k1 in range(len(nested_lst)):
            zgt = 0
            if r_lst[k] == nested_lst[k1][0]:        
                print(freq_lst.index(nested_lst[k1][k2+1] for k2 in range(len(nested_lst[k1]))))
                zgt += r_freq[k] * freq_lst.index(nested_lst[k1][k2+1] for k2 in range(len(nested_lst[k1])))
        mating.append(zgt)
    return mating

但它没有获得频率,只打印了以下内容:

<generator object mating_func.<locals>.<genexpr> at 0x0000020C1D1A8620>
<generator object mating_func.<locals>.<genexpr> at 0x0000020C1D1A8620>
<generator object mating_func.<locals>.<genexpr> at 0x0000020C1D1A8620>
<generator object mating_func.<locals>.<genexpr> at 0x0000020C1D1A8620>
<generator object mating_func.<locals>.<genexpr> at 0x0000020C1D1A8620>

我还尝试过以下方法:

(nested for-loops shown as before)
for k2 in range(len(nested_lst[k1])):
    if rnase_list[k] == zygotes[k1][0]
        zgt += r_freq[k] * freq_lst.index(nested_lst[k1][k2+1])

导致以下错误:

ValueError: 'F1' is not in list

2 个答案:

答案 0 :(得分:2)

mating = []
for k in range(len(r_lst)):
    for lst in nested_lst:
        if r_lst[k] == lst[0]:
            zgt = 0
            zgt+= sum([r_freq[k] * freq_lst[int(i[1:])] for i in lst[1:]])
    mating.append(zgt)

请允许我简化一下。

答案 1 :(得分:1)

这是你正在寻找的东西:

mating = []
for k in range(len(r_lst)):
    for k1 in range(len(nested_lst)):
        if r_lst[k] == nested_lst[k1][0]:
            zgt = 0
            zgt+= sum([r_freq[k] * freq_lst[x] for x in [int(i[1:]) for i in nested_lst[k1][1:]]])
    mating.append(zgt)

输出:

[0.028571430000000002,
 0.05000000400000001,
 0.05000000400000001,
 0.050000002,
 0.07500000600000001]