gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:14:41 25 4
gpt4 key购买 nike

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

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

关于python - 比较相同索引python中列表中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52310348/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com