Python: if element in one list, change element in other?

感情迁移 提交于 2021-02-05 11:12:48

问题


I have two lists (of different lengths). One changes throughout the program (list1), the other (longer) doesn't (list2). Basically I have a function that is supposed to compare the elements in both lists, and if an element in list1 is in list2, that element in a copy of list2 is changed to 'A', and all other elements in the copy are changed to 'B'. I can get it to work when there is only one element in list1. But for some reason if the list is longer, all the elements in list2 turn to B....

def newList(list1,list2):         
    newList= list2[:]  
    for i in range(len(list2)):  
        for element in list1:  
            if element==newList[i]:  
                newList[i]='A'  
            else:
                newList[i]='B'  
    return newList

回答1:


Try this:

newlist = ['A' if x in list1 else 'B' for x in list2]

Works for the following example, I hope I understood you correctly? If a value in B exists in A, insert 'A' otherwise insert 'B' into a new list?

>>> a = [1,2,3,4,5]
>>> b = [1,3,4,6]
>>> ['A' if x in a else 'B' for x in b]
['A', 'A', 'A', 'B']



回答2:


It could be because instead of

newList: list2[:]

you should have

newList = list2[:]

Personally, I prefer the following syntax, which I find to be more explicit:

import copy
newList = copy.copy(list2) # or copy.deepcopy

Now, I'd imagine part of the problem here is also that you use the same name, newList, for both your function and a local variable. That's not so good.

def newList(changing_list, static_list):
    temporary_list = static_list[:]
    for index, content in enumerate(temporary_list):
        if content in changing_list:
            temporary_list[index] = 'A'
        else:
            temporary_list[index] = 'B'
    return temporary_list

Note here that you have not made it clear what to do when there are multiple entries in list1 and list2 that match. My code marks all of the matching ones 'A'. Example:

>>> a = [1, 2, 3]
>>> b = [3,4,7,2,6,8,9,1]
>>> newList(a,b)
['A', 'B', 'B', 'A', 'B', 'B', 'B', 'A']



回答3:


I think this is what you want to do and can put newLis = list2[:] instead of the below but prefer to use list in these cases:

def newList1(list1,list2):         
     newLis = list(list2)
     for i in range(len(list2)):  
          if newLis[i] in list1:  
               newLis[i]='A'  
          else: newLis[i]='B'  
     return newLis

The answer when passed

newList1(range(5),range(10))

is:

['A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B']


来源:https://stackoverflow.com/questions/13578031/python-if-element-in-one-list-change-element-in-other

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!