繁体   English   中英

如何在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)返回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的答案是从字符串中获取字符列表的正确方法。

但是,如果只想移动字符,可以使用chrord函数:

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

在性能方面,制作字母及其值的字典应该更容易,反之亦然。 这样,您每次查询只使用固定时间。 这项更改使您的代码更具可伸缩性,并且速度更快。

使用enumerate()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']

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

既然您已经阐明要尝试使用关键字cipher ,那么更有效的方法是使用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

暂无
暂无

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

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