【问题标题】:iterating over list to increment by 'x' and create new list迭代列表以增加“x”并创建新列表
【发布时间】:2020-03-05 08:54:15
【问题描述】:

我是一名 python 初学者,正在尝试构建一个简单的密码,我在其中迭代一个列表,然后递增 3 以构建一个新列表,但不断收到类型错误。 lower_list = abcd 中的列表.....z

当我执行以下得到一个类型错误:

    for i in lower_list:
        shift_lower += lower_list[i:i+3]

有人提供有关如何在语法上正确执行此操作的任何提示吗?谢谢。

【问题讨论】:

标签: python list iteration


【解决方案1】:

你试试这个。

lower_list=['a','b',...,'z']
cipher_text=[chr(ord(i)+3) for i in lower_list]

['d',
 'e',
 'f',
 ...
 'z',
 '{',
 '|',
 '}']

编辑:

当域和字符范围为a-z时(为简洁起见,我考虑使用小写字母 a-z)。这是 Caeser Cipher 的一个示例。

C.T=(P.T+K)Mod26

实施:

lower_list=['a', 'b' ,'c', ..., 'z']
cipher_text=[chr((ord(s) + incr - 97) % 26 + 97)  for s in lst]

您可以构建一个函数来处理加密和解密。我会这样做。


def caeser_cipher(lst,incr,encrypt=True):
    if encrypt:
        return [chr((ord(s) + incr - 97) % 26 + 97)  for s in lst]
    else:
        return [chr((ord(s) - incr - 97) % 26 + 97)  for s in lst]

lower_letters=['a','b', ...'z']
cipher_text=caeser_cipher(lower_letters,4)
#['e', 'f', 'g', 'h', ... ,'c', 'd']
plain_text=caeser_cipher(cipher_text,4,encrypt=False)
# ['a', 'b', 'c', ...,'z']

【讨论】:

  • 非常感谢 Ch3steR - 成功了!也感谢其他人的建议,并会记住下次更清晰的帖子。
  • @marv77 很高兴为您提供帮助。如果这有帮助,请接受这个作为答案并投票。 ;)
  • 嗨,我需要生成的 cipher_text 来“环绕”并在到达 x、y 和 z 时在 a、b、c 处重新启动。我尝试使用 IF 语句执行此操作,但没有成功。例如。对于 self.lower_list 中的 i: self.cipher_lower += [chr(ord(i) + shift)] if i == [x]: self.cipher_lower = [a] elif i == [y]: self.cipher_lower = [b] elif i == [z]: self.cipher_lower = [c] 但没有运气。我也希望它跳过任何非字母字符。谢谢
  • @marv77 检查编辑后的答案。如果您对我发布的代码有任何疑问,请随时询问。
【解决方案2】:
from string import ascii_lowercase


def encode(original_text: str) -> str:
    return ''.join(
        ascii_lowercase[(ascii_lowercase.index(c) + 3) % len(ascii_lowercase)]
        if c in ascii_lowercase else c
        for c in original_text
    )


print(encode('test xyz'))

输出:

whvw abc

或者你可以为它构建转换地图:

from string import ascii_lowercase


convert_dict = {
    c: ascii_lowercase[(ascii_lowercase.index(c) + 3) % len(ascii_lowercase)]
    for c in ascii_lowercase
}


def encode(original_text: str) -> str:
    return ''.join(
        convert_dict[c]
        if c in convert_dict else c
        for c in original_text
    )


print(encode('test xyz'))

【讨论】:

    【解决方案3】:

    不需要list 来遍历字符串的字符。
    所以我认为你需要这样的东西:

    cipher = 3 # You could use a different cipher value
    message = 'This is an example of Caesars Cipher!'
    encrypted = ''.join(chr(ord(char) + cipher) for char in message)
    decrypted = ''.join(chr(ord(char) - cipher) for char in encrypted)
    print(encrypted)
    print(decrypted)
    

    这段代码输出:

    Wklv#lv#dq#h{dpsoh#ri#Fdhvduv#Flskhu$
    This is an example of Caesars Cipher!
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-03
      • 2014-09-06
      • 2018-02-22
      • 2018-03-19
      • 1970-01-01
      • 2019-07-28
      • 1970-01-01
      • 2018-10-20
      相关资源
      最近更新 更多