0

我有两个列表(长度不同)。一个在整个程序中发生变化(list1),另一个(更长)没有(list2)。基本上我有一个函数应该比较两个列表中的元素,如果一个元素 in ,list1list2副本中的元素list2更改为“A”,副本中的所有其他元素都更改为“B” . 当.中只有一个元素时,我可以让它工作list1。但是由于某种原因,如果列表更长,则所有元素都list2依次为 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
4

3 回答 3

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']
于 2012-11-27T05:53:17.780 回答
0

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']
于 2012-11-27T05:52:35.923 回答
0

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']
于 2012-11-27T05:53:42.333 回答