簡體   English   中英

在Python的另一個列表中從一個列表中查找元素

[英]finding an element from one list in another list in python

有沒有一種方法可以擁有兩個分別名為list1和list2的列表,並能夠查找一個條目在另一個條目中的位置。

list_one = ["0", "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"]

list_two = ["h","e","l","l","o"]

我的目的是允許用戶輸入一個單詞,程序隨后將其轉換為與list_one中的字母條目相對應的一組數字

因此,如果用戶輸入了hello,則計算機將返回85121215(即條目的位置)

有沒有辦法做到這一點

在列表中查找項目的位置不是一個非常有效的操作。 dict是用於此類任務的更好的數據結構。

>>> d = {k:v for v,k in enumerate(list_one)}
>>> print(*(d[k] for k in list_two))
8 5 12 12 15

如果您的list_one始終只是字母(按字母順序排列),則通過使用內置函數ord來使某些功能工作可能會更好,更簡單。

添加到@wim的答案,可以通過簡單的理解來完成。

>>> [list_one.index(x) for x in list_two]
[8, 5, 12, 12, 15]

x.index(i)返回列表x元素i的位置

print("".join([str(list_one.index(i)) for i in list_two]))
85121215

在列表上使用.index()

list_one = ["0", "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"]

string = "hello"
positions = [list_one.index(c) for c in string]
print(positions)
# [8, 5, 12, 12, 15]

您可以反復考慮以下列表:

>>> for i in range(len(list_two)):
...     for j in range(len(list_one)):
...             if list_two[i]==list_one[j]:
...                     list_3.append(j)
>>> list_3
[8, 5, 12, 12, 15]

但是wim的答案更優雅!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM