简体   繁体   English

在python 3.4中将列表的一部分从字符串转换为整数

[英]Converting parts of a list from strings to integers in python 3.4

I'm trying to create a simple Caesar Cypher for a class project, and I can't get past creating the cypher key. 我正在尝试为一个班级项目创建一个简单的Caesar Cypher,但我无法摆脱创建cypher密钥的麻烦。 So far I have: 到目前为止,我有:

import sys
ALPHABET = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','']

def main(text, key):
    print("Encoding message '", text,"'with key",key)
    ALPHABET = generate_cypher(key)

def generate_cypher(ckey):
    cypher = []
    for i in ALPHABET:
        x = ALPHABET[i] + ckey
        cypher = cypher + x
    return cypher

main(sys.argv[1], int(sys.argv[2])

I keep getting this error: TypeError: list indices must be integers, not str 我不断收到此错误:TypeError:列表索引必须是整数,而不是str

The line for i in ALPHABET is iterating over the elements in ALPHABET not the indices. 线for i in ALPHABET被迭代中的元素ALPHABET不索引。 So its going 'a', 'b', 'c', etc. You want to use for i in range(len(ALPHABET)) if you want to iterate over the indices. 因此它的行数为'a','b','c'等。如果要遍历索引, for i in range(len(ALPHABET))使用for i in range(len(ALPHABET))

The error is telling you that ALPHABET[i] is failing as i is not an integer. 该错误告诉您ALPHABET[i]失败,因为i不是整数。 In this case the first iteration is the letter a so it is trying to do ALPHABET['a'] which won't work and returns the error. 在这种情况下,第一个迭代是字母a因此它将尝试执行ALPHABET['a'] ,该方法将不起作用并返回错误。 That is why you need to iterate over the indices not the elements. 这就是为什么您需要遍历索引而不是元素的原因。

Assuming ckey is intended to be an integer for the offset of the cypher you can fix you code with the following: 假设ckey旨在为密码偏移量的整数,则可以使用以下代码来修复代码:

Credit to @AChampion on a nice little trick for the index length 感谢@AChampion一个关于索引长度的小技巧

def generate_cypher(ckey):
    cypher = []
    for i in range(len(ALPHABET)):
        x = ALPHABET[(i+ckey)%len(ALPHABET)]
        cypher.append(x)
    return cypher

Notice that I added some logic to fix the situation at the end of your iteration where the index will be beyond the available indices of the list. 注意,我在迭代结束时添加了一些逻辑来修复这种情况,即索引将超出列表的可用索引。 The cypher needs to wrap around to the beginning at this point thus the necessity of the modulo for ensuring that the index will never be larger than the size of ALPHABET. 密码需要在此时绕到开头,因此有必要使用模以确保索引永远不会大于ALPHABET的大小。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM