【发布时间】: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