繁体   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