在 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,计算机将 return 85121215(作为条目的位置)

有没有办法做到这一点

查找项目在列表中的位置不是一个非常有效的操作。对于这种任务,字典是一种更好的数据结构。

>>> 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 可能会更好更简单。

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

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 的回答更优雅!

添加到@wim 的回答中,可以通过简单的理解来完成。

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