比较两个列表并创建第三个列表

时间:2016-06-15 09:59:18

标签: python list

鉴于,

list1= ['hello', 'say', 'morning', 'ironman', 'sayonara', 'king', 'yellow']  
list2= ['say', 'king', 'yellow']  

我想获得一个像这样的list3:

list3= ['0', 'say', '0', '0', '0', 'king', 'yellow']  

所以我想获得list1大小和单词不一样的地方我想放一个0.

我尝试:

list1= ['hello', 'say', 'morning', 'ironman', 'sayonara', 'king', 'yellow']
list2= ['say', 'king', 'yellow']
list3 = list()
for i in list1:
     for j in list2:
          if(i=j):
              list3.append(i)
          else (i!=j):
              list3.append('0')

3 个答案:

答案 0 :(得分:2)

使用list comprehensions在一行中编写代码,

list1= ['hello', 'say', 'morning', 'ironman', 'sayonara', 'king', 'yellow']
list2= ['say', 'king', 'yellow']

list3 = [s if s in list2 else '0' for s in list1]

print(list3)
['0', 'say', '0', '0', '0', 'king', 'yellow']

PS:将list2转换为set以加快速度。

答案 1 :(得分:0)

基本上,您只需使用第一个列表中的每个元素迭代第二个列表。如果它们匹配,则可以跳出第二次迭代并将找到的元素追加到结果中,否则追加" 0"。像这样:

list1 = ['hello', 'say', 'morning', 'ironman', 'sayonara', 'king', 'yellow']  
list2 = ['say', 'king', 'yellow']  
result = [];
for word in list1:
    found = False;
    for testWord in list2:
        if(word == testWord):
            found = True;
            break;
    if found == True:
        result.append(word)
    else:
        result.append("0")


print(result) 
//prints ['0', 'say', '0', '0', '0', 'king', 'yellow']

答案 2 :(得分:0)

一个for循环应该可以解决问题:

list1= ['hello', 'say', 'morning', 'ironman', 'sayonara', 'king', 'yellow']  
list2= ['say', 'king', 'yellow']

result = []
for word in list1:
    if word in list2:
        result.append(word)
    else:
        result.append("0")
print(result)

# Output
['0', 'say', '0', '0', '0', 'king', 'yellow']