从python中的另一个列表中的一个列表中查找元素

问题描述 投票:1回答:5

有没有办法让两个名为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中的字母条目对应的一组数字

所以如果用户输入你好,计算机将返回85121215(作为条目的位置)

有没有办法做到这一点

python list elements
5个回答
8
投票

查找列表中项目的位置不是一个非常有效的操作。对于这种任务,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可能会更好更简单。


2
投票

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

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

0
投票

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

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

0
投票

在列表中使用.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]

0
投票

你可以遍历列表:

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

© www.soinside.com 2019 - 2024. All rights reserved.