简体   繁体   English

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

[英]how can I move a list index value forward 'x' amount of times using python?

I'm trying to unscramble a code using pythonic methods. 我正在尝试使用pythonic方法解密代码。 The way to crack the code is by selecting the letter two places ahead of itself. 破解代码的方法是选择前面两个字母的字母。

For example if the code was 例如,如果代码是

abc

Then the solution would be 那么解决方案就是

cde

So I am trying to figure out how I add 2 to the index value of a letter (given it is in a list like the following) 所以我试图找出如何将2添加到字母的索引值(假设它在如下列表中)

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

I am trying to write code similar to this 我正在尝试编写类似于此的代码

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="")

But I am not yet skilled enough in python to figure it out 但我在python中还不够熟练,无法弄明白

Try: 尝试:

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

The above is not limited to standard ASCII: it works up through the unicode character set. 以上不限于标准ASCII:它通过unicode字符集进行处理。

Limiting ourselves to 26 characters 将自己限制在26个字符

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

Modifying the original code 修改原始代码

If we want to modify the original only enough to get it working: 如果我们想要仅修改原始文件以使其正常工作:

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="")

Example: 例:

>>> scramble('abcz')
cdeb

One solution would be to use enumerate: 一种解决方案是使用枚举:

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

This way you could index in by adding to idx. 这样您就可以通过添加到idx来索引。 Make sure you check for the end of the list though. 请确保检查列表的末尾。

You could also wrap around the list by using modulus on the length of the list, so if you added 2 to the index 25 in a 26 element list, you would get 27 % 26 = 1, so the second element of the list again. 你也可以通过在列表长度上使用模数来回绕列表,所以如果你在26元素列表中的索引25中添加2,你将得到27%26 = 1,所以再次列表的第二个元素。

There are a couple of ways to do this. 有几种方法可以做到这一点。

First one, use a dictionary. 首先,使用字典。

a={'a':'c','b':'e'....}
sol=[]
for i in sentence:
    sol.append(a[i])
alphabet = "abc"
ord_a = ord('a')
solution = ''.join(chr((ord(c)-ord_a+2)%26+ord_a) for c in alphabet)

Something like this would be useful because it would allow you to change your offset value easily. 这样的东西会很有用,因为它可以让你轻松改变你的偏移值。 It'll also handle things other than characters 它还可以处理字符以外的东西

def caesar_cipher(sentence, offset):
   pt_alphabet = ['a','b'...'z']
   ct_alphabet = []
   index = len(pt_alphabet) + offset
   while len(ct_alphabet) < len(pt_alphabet):
      if index < (len(pt_alphabet) - 1):
         ct_alphabet.append(pt_alphabet[index])
         index += 1
      else:
         index -= len(pt_alphabet)
   out_word = ''
   for character in sentence:
      if character.lower() not in pt_alphabet:
         out_word += character
      if character.lower() in pt_alphabet:
         out_word += ct_alphabet[pt_alphabet.index(character.lower())]
   return out_word

if __name__ == '__main__':
   offset = 2
   sentence = "This is a test with caps and special characters!!"
   cipher_text = caesar_cipher(sentence, offset)
   print sentence
   print cipher_text

Usage like this: 用法如下:

$ python cipher.py
>> This is a test with caps and special characters!!
>> vjku ku c vguv ykvj ecru cnf urgekco ejctcevgtu!!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 python 中调用 function“x”次? 使用 for 循环? - How do I call a function "x" amount of times in python? Using a for loop? 使用 Python 3 时,如何避免 IndexError: list index out of range 当范围可以是随机拆分数量时? - How can I avoid IndexError: list index out of range when the range can be random amount of splits, using Python 3? 如何在x倍的时间内每x秒发送send_message呢? 随着tkinter进口 - How can I implement this to send_message every x amount of seconds for x amount of times? With tkinter imports Python Pandas 根据x值重复一个值x次数 - Python Pandas Repeat a value x amount of times according to x value 我如何从列表中随机选择用户要求在 python 中使用输入的次数? - how do i randomly pick characters out of a list the amount of times the user asks for using input in python? Python - 如何按 X 量移动字符串中的字符 - Python - How to move characters in string by X amount 如何计算使用python显示字母的次数? - How do I count the amount of times a letter appears using python? 如何使用python从列表中获取字典,将列表条目作为键,并将列表中的项数作为值? - How do I obtain a dictionary from a list, with list entrys as key and the amount of the items in the list as value, using python? 在Python中打印x次数 - Printing x amount of times in Python 如何为工作表中的 X 个单元格设置值? - how can i set a value for X amount of cells in a worksheet?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM