【问题标题】:Find list items, that contain items from other list in python [duplicate]在python中查找包含其他列表中的项目的列表项[重复]
【发布时间】:2022-01-24 17:44:46
【问题描述】:

我正在尝试编写一个查询,如果列表项包含其他列表中的单词,则可以返回给我。

Words = [ ‘fuel’ , ‘regular’ , ‘clause’ , ‘maximum’ ]

KP = [ ‘ fuel surcharge policy ‘ , ‘Rsp’ , ‘ liability clause’ , ‘Volume’ ] 

Output = [ ‘ fuel surcharge‘  , liability clause’ ]

上面的输出是预期的,因为它包含第一个列表中的“燃料”和“条款”。

我正在使用下面的代码,但我得到的是 NA 作为输出。

Output = []
for i,j in zip (Words, KP):
        if i in j:
            Output.append (j)
        else:
            print ('NA")

【问题讨论】:

  • 使用两个 for 循环而不是一个压缩的循环,它会工作得很好。

标签: python python-3.x list python-2.7 for-loop


【解决方案1】:

你可以试试:

Words = [ "fuel" , "regular" , "clause" , "maximum" ]
       
KP = [ "fuel surcharge policy " , "Rsp" , "liability clause" , "Volume" ]

output=[]
for data in KP:
    for word in data.split():
        if word in Words:
            output.append(data)

print(output)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-03
    • 2022-01-04
    • 2018-07-07
    • 2019-03-06
    • 1970-01-01
    • 2016-05-18
    相关资源
    最近更新 更多