从Python中的列表中选择元素

时间:2016-03-11 03:24:36

标签: python string

尝试获取用户输入,在“alphabet”变量中找到这些元素的索引,存储它们,在“key”变量中找到相同索引的元素,然后将它们打印出来。这是我到目前为止所做的,但无法从“key”变量中获取要打印的元素......

key =   "XPMGTDHLYONZBWEARKJUFSCIQV"
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
plain = input("Type something: ").upper()
result = [alphabet.index(i) for i in plain]
print (result)
coded = [result.?(i) for i in key]
print (coded)

3 个答案:

答案 0 :(得分:0)

我不是100%确定我正确地理解了这个问题,但是如果我这样做了,那么这段代码就可以了

key =   "XPMGTDHLYONZBWEARKJUFSCIQV"
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
plain = input("Type something: ").upper()
result = []
for letter in plain:
    if letter in alphabet: result.append(letter)
print (result)
coded = []
for i in range(len(result)):
    if result[i] == key[i]: coded.append(result[i])
print (coded)

答案 1 :(得分:0)

一旦获得索引(在result列表中),只需在key列表的相同索引处打印出元素即可。你应该简单地写这行

coded = [result.?(i) for i in key]

作为

coded = [key[i] for i in result]

答案 2 :(得分:0)

一个选项是operator.itemgetter。它用于创建一个函数,该函数将从其参数中通过索引获取一个或多个项目。

from operator import itemgetter

key =   "XPMGTDHLYONZBWEARKJUFSCIQV"
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
plain = input("Type something: ").upper()
result = [alphabet.index(i) for i in plain]
print (result)
coded = itemgetter(*result)(key)  # Returns a tuple
# coded = ''.join(coded)          # Make a string from the tuple
print (coded)