这是我的整个代码

a = str(input("parent1 :"))
b = str(input("parent2 :"))


p = {'rose':'R_P_', 'pea':'rrP_'}
print(p[a] +" : "+p[b])

f = []

print('gamet 1 : ' + p[a][0]+p[a][2])
print('gamet 2 : ' + p[b][0]+p[b][2])

g = f

aa=(sorted(p[a][0]+p[b][0]))
bb=(sorted(p[a][2]+p[b][2]))

def convert(s):

    # initialization of string to ""
    new = ""

    # traverse in the string
    for x in s:
        new += x

    # return string
    return new

gamet = convert(aa)+convert(bb)
gamet1 = list(gamet)
print(gamet +" x " + gamet)

dictgen = {0:gamet[0]+gamet[2], 1:gamet[0]+gamet[3], 2:gamet[1]+gamet[2], 3:gamet[1]+gamet[3]}
l=0
ll=0
gen={}
for k in range(len(dictgen)):
    for j in range(4):
        gen[l] = dictgen[k].join(dictgen[j])
        l += 1
print(gen)
genn={}
for x in range(4):
    for p in range(4):
        genn[ll]=(sorted(convert(gen[p])))
        ll += 1

print(genn)

gen1=[]
for x in range(0,15):
    gen1[x]=genn[x][0].join(genn[x][1])

print(gen1)



这是关于genn中的价值的例子
{0:['P','P','R','R'],1:['P','P','R','R'],2:['P','P ','R','r'],3:['P','P','R','r'],4:['P','P','R','R'] ,5:['P','P','R','R'],6:['P','P','R','r'],7:['P','P ','R','r'],8:['P','P','R','R'],9:['P','P','R','R'] ,10:['P','P','R','r'],11:['P','P','R','r'],12:['P','P ','R','R'],13:['P','P','R','R'],14:['P','P','R','r'] ,15:['P','P','R','r']}

我想使用此代码按Genn词典值中的索引[0]和[1]取值
gen1 = []

for x in range(0,15):
    gen1[x]=genn[x][0].join(genn[x][1])

print(gen1)


我有错误

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-25-3f9d7067d375> in <module>
     51 gen1=[]
     52 for x in range(0,15):
---> 53     gen1[x]=genn[x][x][0].join(genn[x][x][1])
     54
     55 print(gen1)

IndexError: string index out of range

最佳答案

您说过要运行的代码与实际运行的代码不同。

for x in range(0,15):
    gen1[x]=genn[x][0].join(genn[x][1])


与...不同

for x in range(0,15):
    gen1[x]=genn[x][x][0].join(genn[x][x][1])


x为0。

genn[0] # -> ['P', 'P', 'R', 'R']
genn[0][0] # -> 'P'
genn[0][0][1] # -> IndexError: string index out of range

08-04 18:07