【问题标题】:Comparing items in lists within same indices python比较相同索引python中列表中的项目
【发布时间】:2018-09-13 09:09:53
【问题描述】:

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

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"]

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

对于“深蓝色”和“天空是蓝色”的第 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

【问题讨论】:

  • 结果的顺序是否重要,例如预期结果中第二项的“粉红色”与“浅粉色”?

标签: python python-2.7 list for-loop


【解决方案1】:

使用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']

【讨论】:

    【解决方案2】:

    您可以使用以下列表推导:

    print([' '.join(w for w in i.split() if w in c.split()) for c, i in zip(colours, items)])
    

    这个输出:

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

    【讨论】:

    • 为什么需要第二次拨打split?
    • 一个split 用于items,另一个split 用于colours。如果 OP 不关心匹配单词并且只需要子字符串匹配,那么就不需要c.split()(对于colours)。
    • 如果说items[0] 是'"the sun is yellowish but the sunset is red "',则不返回'yellow'。我认为这是正确的。我将删除我的答案。
    • 谢谢,结果就是我要找的。​​span>
    【解决方案3】:

    使用集合来测试成员资格应该更快,但需要注意的是:

    >>> [' '.join(set(colour.split()) & set(item.split())) 
         for colour, item in zip(colours, items)]
    ['yellow', 'pink light', 'red', 'blue', 'red']
    

    需要注意的是,集合是无序的,因此“粉红色的光”可能会以“浅粉色”的形式出现。

    【讨论】:

      猜你喜欢
      • 2014-03-13
      • 1970-01-01
      • 1970-01-01
      • 2020-08-18
      • 1970-01-01
      • 2021-06-25
      • 1970-01-01
      • 2012-07-10
      • 1970-01-01
      相关资源
      最近更新 更多