`
def key_gen(l):
lettersi = ()
for a in range(l[0], l[4]):
letters1 = lettersi + (a,)
for b in range(l[5], l[9]):
letters2 = lettersi + (b,)
for c in range(l[10], l[14]):
letters3 = lettersi + (c,)
for d in range(l[15], l[19]):
letters4 = lettersi + (d,)
for e in range(l[20], l[24]):
letters5 = lettersi + (e,)
key = letters1 + letter2+ letter3 + letters4 + letters5
return key
`
我运行它,而我在python shell上运行...:
letters = ('A','B','C','D','E','F', 'G','H','I','J', ' ', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'X', 'Z', '.')
>>>key_gen(letters)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in key_gen
TypeError: 'str' object cannot be interpreted as an integer
我不知道我在这里犯了什么错误,因为我是python的初学者,但我希望输出是这样的。你知道怎么解决它吗?
>>>key_gen(letters)
((‘A’, ‘B’, ‘C’, ‘D’, ‘E’), (‘F’, ‘G’, ‘H’, ‘I’, ‘J’), (‘ ’, ‘L’, ‘M’, ‘N’, ‘O’), (‘P’, ‘Q’, ‘R’, ‘S’, ‘T’), (‘U’, ‘V’, ‘X’, ‘Z’, ‘.’))
也许我定义的函数不能读取字符串元组,但我不知道该怎么做,我已经google了它,无法找到任何东西。
答案 0 :(得分:3)
range()
期望其参数为int
类型,并且通过传递l[0]
,您实际上将其作为char 'A'
传递。我想你想做的是:
for a in range(0, 4):
letters1 = lettersi + (l[a],)
# instead of:
# for a in range(l[0], l[4]):
# letters1 = lettersi + (a,)
有一些现有的方法可以实现您想要实现的目标。请参阅:How do you split a list into evenly sized chunks?。但那里我没有提到我会做的事情。我的方法是将列表切片与 list comprehension 一起使用:
>>> [letters[i:i+5] for i in range(0, len(letters), 5)]
[('A', 'B', 'C', 'D', 'E'), ('F', 'G', 'H', 'I', 'J'), (' ', 'L', 'M', 'N', 'O'), ('P', 'Q', 'R', 'S', 'T'), ('U', 'V', 'X', 'Z', '.')]