0

我想学习python,我想在没有任何模块或库的情况下更改字母我尝试了这样的方法,但它不起作用:

d=list('banana')
a=list('abcdefghijklmnopqrstuvwxyz')

for i in range:
    d[i]=a[i+2]
print d

我收到了这个错误:

TypeError: 'builtin_function_or_method' object is not iterable

如果您能帮助我,我将不胜感激。

4

3 回答 3

3

您忘记为范围函数指定参数:

d=list('banana')
a=list('a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z')

for i in range(len(d)):
    d[i]=a[i+2]
print d

来自 python 文档:

range(start, stop[, step]) 这是一个通用函数,用于创建包含算术级数的列表。它最常用于 for 循环。参数必须是纯整数。如果省略 step 参数,则默认为 1。如果省略 start 参数,则默认为 0。完整形式返回纯整数列表 [start, start + step, start + 2 * step, ...] . 如果step为正,则最后一个元素是最大的start + i * step小于stop;如果 step 为负数,则最后一个元素是最小的 start + i * step 大于 stop。step 不能为零(否则会引发 ValueError)。例子:

>>>
>>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5)

根据请求编辑:

d = list('banana')
a = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
mappings = dict((ch, a[idx+2]) for idx, ch in enumerate(set(d)))

for idx in range(len(d)):
    d[idx] = mappings[d[idx]]
#OR:
d = [mappings[d[idx]] for idx in range(len(d))]

print d
于 2012-11-18T08:31:48.160 回答
1

string.translate 非常适合这个......我不确定这是否算作图书馆......

>>> import string
>>> tab = string.maketrans("abcdefghijklmnopqrstuvwxyz","mnopqrstuvwxyzabcdefghi
jkl")
>>> print "hello".translate(tab)
tqxxa

或者

>>> print  "".join([chr(ord(c)+13) if ord(c) + 13 < ord('z') else chr(ord('a')+(ord(c)+13)%ord('z')) for c in "hello"])
'uryyc'
于 2012-11-18T08:34:27.277 回答
1
In [63]: d=list('aabbcc')

In [64]: a='a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z'.split(",")

In [65]: for i,x in enumerate(d):
    d[i]=a[(a.index(x)+3)%26]

In [66]: d
Out[66]: ['d', 'd', 'e', 'e', 'f', 'f']
于 2012-11-18T08:45:41.157 回答