如何使用python将列表索引值向前移动'x'次?

2024-04-27 20:56:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我在试着用pythonic方法解读代码。破解代码的方法是先选择字母的两个位置。你知道吗

例如,如果代码

abc

那么解决办法就是

cde

因此,我试图找出如何将2添加到一个字母的索引值中(假设它位于下面的列表中)

alphabet = ["a","b","c"...."z"]

我正在尝试编写与此类似的代码

def scramble(sentence):
    alphabet = ["a","b","c"...]
    solution = []
    for i in sentence:
        newIndex = get index value of i, += 2
        newLetter = translate newIndex into the corresponding letter
        solution.append(newLetter)
    for i in solution:
        print(i, end="")

但我还没有掌握足够的python来解决这个问题


Tags: 方法代码in列表for字母pythonicsentence
3条回答

尝试:

>>> s = 'abc'
>>> ''.join(chr(ord(c)+2) for c in s)
'cde'

以上内容并不局限于标准ASCII:它通过unicode字符集工作。你知道吗

限制在26个字符以内

>>> s = 'abcyz'
>>> ''.join(chr(ord('a')+(ord(c)-ord('a')+2) % 26) for c in s)
'cdeab'

修改原始代码

如果我们只想修改原始文件以使其工作:

from string import ascii_lowercase as alphabet

def scramble(sentence):
    solution = []
    for i in sentence:
        newIndex = (alphabet.index(i) + 2) % 26
        newLetter = alphabet[newIndex]
        solution.append(newLetter)
    for i in solution:
        print(i, end="")

示例:

>>> scramble('abcz')
cdeb

一种解决方案是使用枚举:

for idx, char in enumerate(sentence):
    # Do what you need to do here, idx is the index of the char, 
    # char is the char itself
    letter = sentence[idx + 2] # would get you the char 2 places ahead in the list

这样,您可以通过添加到idx来索引。但一定要检查一下列表的末尾。你知道吗

您还可以通过对列表长度使用模数来环绕列表,因此如果在26个元素的列表中的索引25中添加2,则会得到27%26=1,因此再次使用列表的第二个元素。你知道吗

有几种方法可以做到这一点。你知道吗

第一,使用字典。你知道吗

a={'a':'c','b':'e'....}
sol=[]
for i in sentence:
    sol.append(a[i])

相关问题 更多 >