在Python中从列表中选择元素
尝试获取用户输入,在“alphabet”变量中找到这些元素的索引,存储它们,在“key”变量中找到相同索引的元素,然后打印出来。这是我到目前为止所拥有的,但无法从“key”变量中获取要打印的元素在Python中从列表中选择元素,python,string,Python,String,尝试获取用户输入,在“alphabet”变量中找到这些元素的索引,存储它们,在“key”变量中找到相同索引的元素,然后打印出来。这是我到目前为止所拥有的,但无法从“key”变量中获取要打印的元素 key = "XPMGTDHLYONZBWEARKJUFSCIQV" alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" plain = input("Type something: ").upper() result = [alphabet.index(i) for i
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)
我不是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)
一旦获得索引(在结果
列表中),只需打印出键
列表中相同索引处的元素即可。你只要写这行就行了
coded = [result.?(i) for i in key]
作为
一个选择是。它用于创建一个函数,该函数将从其参数中按索引获取一个或多个项
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)
这不是一种方法。使用
结果[i]
。好的,从技术上讲,这只是结果的快捷方式。uuu getitem_uuu(i),但无论如何……你有3个解决方案,0,投票,0个接受答案,0个评论。他们中有谁对你有用吗?这就成功了!非常感谢你!在“i for i”函数中使用括号和方括号有什么区别?方括号用于列表索引(在本例中),而圆括号用于其他事情,如方法参数、元组创建等。
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)