如何从 python 中的位置(我使用 index() 找到的)查找列表中的元素

How to find an element in a list from its position(which i found using index()) in python

alpha = ["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"]

这是列表

for letters in sentence:
    pos2 = alpha.index(letters) + 1
    #to find the positions of each letter
    new_sentence.append(pos2)
    #to add each position to the empty list
print (new_sentence)

这就是我用来在字母列表中查找输入消息中每个字母的位置的方法

现在我想把它转换回位置的字母..

你可以索引它:

[alpha[p-1] for p in new_sentence]

sentence = "helloworld"
# ... run your code to get the new_sentence
''.join(alpha[p-1] for p in new_sentence)

# 'helloworld'

如果您打算在原始字母之后查找字母,您可以从评论@RushyPanchal 中获取索引的其余部分:

sentence = "hello world"

# ... run your code to get the new_sentence
''.join(alpha[p % len(alpha)] for p in new_sentence)

# 'ifmmpxpsme'

因为您有索引,所以您可以获取该索引处的值。

print my_list[pos2]

python 也有一个内置方法 enumerate(enumerable_obj) returns index, value

for index, value in enumerate(my_list):
    print index, value
alpha_text = ""
for i in new_sentence:
    alpha_text = alpha_text + alpha[i - 1]
print(alpha_text)

所以你的整个代码看起来像:

sentence = "lololololololololol" #your text
alpha = ["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"]
new_sentence = []
for letters in sentence:
    pos2 = alpha.index(letters) + 1
    #to find the positions of each letter
    new_sentence.append(pos2)

print (new_sentence)
alpha_text =""
for i in new_sentence:
    alpha_text = alpha_text + alpha[i - 1]
print(alpha_text)

输出:

 [12, 15, 12, 15, 12, 15, 12, 15, 12, 15, 12, 15, 12, 15, 12, 15, 12, 15, 12]

 lololololololololol

@Psidom 的回答是从字符串中获取字符列表的正确方法。

但是,如果您只想移动字符,可以使用 chr and ord 函数:

sentence = "some string"
shifted_sentence = ''.join(chr(ord(c)+1) for c in sentence)

就性能而言,制作字母及其值的字典应该更容易,反之亦然。这样你每次查找只使用一个固定的时间。此更改使您的代码更具可扩展性和速度。

您当前的方法效率低下,因为您必须为输入句子中的每个字母搜索多达 26 个不同的列表项。对于字母 "z",它也失败了,因为列表中 "z" 之后没有任何内容。

既然你已经澄清你正在尝试做一个 keyword cipher, a more efficient method would be to use str.translate:

import string

keyword = 'stack'
source = string.ascii_lowercase
target = keyword + ''.join(filter(lambda x: x not in keyword, source))

sentence = 'encode me'
encoded = sentence.translate(str.maketrans(source, target))

print(encoded)

输出:

klamck jk

使用enumerate() and filter()的方法:

>>> sentence = 'hello'

对于这个例子是:

>>> new_sentence
[8, 5, 12, 12, 15]

结果如下:

>>> letters_enum = [(j,c) for j,c in enumerate(alpha, 1) if j in new_sentence]
>>> result = []
>>> for i in new_sentence:
...     letter = list(filter(lambda item: item[0] == i, letters_enum))
...     result.extend(letter[0][1]*len(letter))
...
>>>
>>> result
['h', 'e', 'l', 'l', 'o']