簡體   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