Skip to main content
 首页 » 编程设计

python之比较相同索引python中列表中的项目

2025年05月04日11Leo_wl

我想比较两个列表并提取内容

colours = ["yellow", "light pink", "red", "dark blue", "red"] 
 
items = ["the sun is yellow but the sunset is red ", 
         "the pink cup is pretty under the light",  
         "it seems like the flower is red",  
         "skies are blue", 
         "i like red"] 

预期结果:

["yellow", "pink light", "red", "blue", "red"] 

如果颜色列表中有两个词,该项目将被分解为两个词。 如您所见,颜色词(“粉红色”、“浅色”)的顺序并不重要,因为这两个词被分解成单独的词,然后在句子中单独进行比较。请注意,在项目中的第一个项目中,虽然颜色列表中有“红色”,但我不想提取它,因为“红色”与项目的索引在不同的索引中。

对于“深蓝色”和“天空是蓝色”的第 4 个索引,结果应该只显示“蓝色”,因为项目中不存在深色。

我尝试编写代码,但我得到的结果是列表没有在相同索引中进行一次比较,而是循环了很多次,因此重复了“红色”。

colours=["yellow","light pink","red"," dark blue","red"] 
 
items=["the sun is yellow but the sunset is red ","the pink cup is pretty under the light", "it seems like the flower is red", "skies are blue","i like red"] 
 
for i in colours: 
 
y=i.split() #split 2 words to 1 word 
    for j in y: 
    #iterate word by word in colours that have more than 1 word 
        for z in items:  
            s=z.split() #split sentences into tokens/words 
            for l in s: 
            #compare each word in items with each word in colours 
                if j == l: 
                    print j 

结果:

yellow 
light 
pink 
red 
red 
red 
blue 
red 
red 
red 

正确结果:

yellow 
pink light  
red 
blue 
red 

请您参考如下方法:

使用zip,你可以做的更简单:

colours=["yellow","light pink","red"," dark blue","red"] 
 
items=["the sun is yellow but the sunset is red ","the pink cup is pretty under the light", "it seems like the flower is red", "skies are blue","i like red"] 
 
lst = [] 
for x, y in zip(colours, items): 
    word = '' 
    for c in y.split(): 
        if c in x: 
            word = word + ' ' + c 
    lst.append(word.strip()) 
 
print(lst) 
# ['yellow', 'pink light', 'red', 'blue', 'red']