Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

Convert int into str while in __getitem__ Python 2.7

Okay, i have this string:

string = "HelloWorld"

And for this example, I am using a dictionary similar to this:

dic = [{'a':'k','b':'i'},{'a':'i','b':'l'},{'a':'x','b':'n'},{'a':'q','b':'o'}]

Now.. I need to reference a dictionary from the list, so that I can change the characters in my string. To do so normally I would just do this:

dic[#]

But in this case I also need a value from that dictionary. Now I tried this:

dic[int(char[i[letter]])]

But I get the error:

'int' object has no attribute '__getitem__'

Searching for the error gives me answers here on StackOverflow, but they do not fix my problem.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's my best crystal ball guess at what you want. The keys of your dictionary are only a and b, which aren't any characters in HelloWorld, but if you actually had characters from your string as keys like the following, this is how I'd do the replacement, assuming you want to rotate through the four different dictionaries:

string = "HelloWorld"
D = [{'H':'a','o':'e','l':'i'},{'e':'b','W':'f','d':'j'},{'l':'c','o':'g'},{'l':'d','r':'h'}]
print ''.join(D[i%4][c] for i,c in enumerate(string))

Output:

abcdefghij

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...