您可以使用zip()
来配对多个列表的元素:
key = (12, 31, 42, 1, 23, -12) # a tuple
inputstring = 'abcdef'
for char, keyval in zip(map(ord, inputstring), key):
# do something with the char ordinal and the key value.
这确实假设您的密钥至少与输入字符串一样长。
如果您的输入键是固定长度并且您想重复使用它,您可以使用该itertools.cycle()
函数重复循环键并将键值与字符串配对,直到字符串中的字符用完:
from itertools import cycle
key = (12, 31, 42, 1, 23, -12) # a tuple
inputstring = 'abcdefghijkl'
for char, keyval in zip(map(ord, inputstring), cycle(key)):
# do something with the char ordinal and the key value.
演示:
>>> from itertools import cycle
>>> key = (12, 31, 42, 1, 23, -12)
>>> inputstring = 'abcdefghijkl'
>>> for char, keyval in zip(map(ord, inputstring), cycle(key)):
... print char, keyval
...
97 12
98 31
99 42
100 1
101 23
102 -12
103 12
104 31
105 42
106 1
107 23
108 -12
在这里,键值重复,因为它们与输入字符串的序数配对。