尝试比较两个列表,找到相等的值并将它们替换为另一个列表的索引,但它不起作用

Trying to compare two lists, find the equal values and replace them with the index of the other list, but it is not working

基本上,我有一个列表,其中包含第二个列表的所有可能值。例如:

第一个列表(可能的值):

list1 = ['cat','dog','pig'] 

第二个列表:

list2 = ['dog','cat','cat','cat','dog','pig','cat','pig']

我想比较这些列表并将第二个列表中的所有字符串替换为第一个列表的索引。

所以期待这样的事情:

list2 = [1,0,0,0,1,2,0,2]

我试过几种不同的方法。第一个虽然有效,但不是一个聪明的方法。因为如果第一个列表具有大量不同的可能值,则此策略将不适用于代码。

这是第一个解决方案:

list3 = []
for i in list2:
    if i == 'cat':
        i = 0
        list3.append(i)
    elif i == 'dog':
        i = 1
        list3.append(i)
    elif i == 'pig':
        i = 2
        list3.append(i)
    list2 = list3


print(list2)

输出

[1, 0, 0, 0, 1, 2, 0, 2]

但我想要一个解决方案,它可以在大量可能的值中工作,而不必为每个测试编写代码。

所以我尝试了这个(以及其他失败的尝试),但它不起作用

for i in list2:
    for j in list1:
        if i == j:
            i = list1.index(j)

您的代码存在的问题是您只是在每次迭代时替换 i。您想要创建一个 list 并在每次迭代时将 list1.index(j) 的结果附加到它:

 l = []
for i in list2:
    for j in list1:
        if i == j:
            l.append(list1.index(j))

请注意,这可以通过列表理解来简化:

[list1.index(i) for i in list2]
# [1, 0, 0, 0, 1, 2, 0, 2]

请注意,对于较低复杂度的解决方案,您可以创建一个字典映射字符串以进行索引,并通过查找 list2 中的字符串来简单地创建一个列表,如@blhshing 的回答。


一些您可能会觉得有用的读物​​:

您通过迭代列表获得的 i 不会将更改反映回列表中。因此没有变化。


创建一个将动物映射到索引位置的字典。

使用列表理解通过替换 list2 其查找索引的动物来创建新列表:

list1 = ['cat','dog','pig']

lookup = {animal:index for index,animal in enumerate(list1)}

list2 = ['dog','cat','cat','cat','dog','pig','cat','pig']

result = [lookup.get(what) for what in list2]

print(result) # [1, 0, 0, 0, 1, 2, 0, 2]

独库:

您可以使用字典理解创建映射字典,使用 enumerate 函数将键映射到索引,然后将 list2 中的项目映射到映射字典的值:

mapping = {k: i for i, k in enumerate(list1)}
list(map(mapping.get, list2))

这个returns:

[1, 0, 0, 0, 1, 2, 0, 2]

只能使用一种for loop和一种易于理解的if-statement

list1 = ['cat','dog','pig']
list2 = ['dog','cat','cat','cat','dog','pig','cat','pig']

for i,item in enumerate(list2):
    if item in list1:
        list2[i] = list1.index(item)       

# list2 = [1, 0, 0, 0, 1, 2, 0, 2]