如何比较单词和字符串列表,然后使用python打印包含单词的完整字符串? [英] How to compare lists of words and strings, then to print full string that contains word using python?

查看:68
本文介绍了如何比较单词和字符串列表,然后使用python打印包含单词的完整字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比较python中的2个列表.第一个列表包含单词,第二个列表包含字符串/行.如果在list2(字符串)中找到了list1中的任何单词,则打印完整匹配的字符串/行.

Compare 2 lists in python. First list contain words and second list with strings/lines. If any word in list1 is found in list2 (strings), then print full matched string/lines.

list1=["watch","hour","time"]

list2=["new watch rolex","time","digital watch","minutes hour second"]

输出:

new watch rolex,time,digital watch,minutes hour second

推荐答案

如果要检查字符串i是否包含字符串j,可以在j中使用i进行操作.接下来是部分您实际如何想要输出.我的方法是遍历list1,然后让每个对象都经过list2,然后检查list2的元素是否包含list1的元素.如果包含则我检查它们是否相等.如果相等,我会跳过它们.否则,我已经打印了list2的元素.

If you want to check if a string i contains string j, you can do it using i in j. Then comes the part how do you want the output actually. What my approach was to go through the list1 and for each of them go though the list2 and check if element of list2 contains the element of list1. If contains then i checked if they are equal or not. If equal i skipped them. Otherwise i have printed the element of list2.

如@mathius所示,我的代码将多次打印list2的同一元素.我没有处理这个问题,因为对我来说,邮递员不想要那个.期待您的意见.这是我的代码:

As @mathius indicated, my code will print the same element of list2 more than once. I didn't handle that because to me, post maker didn't want that. Look forward to your opinion. Here is my code:

for i in list1:
    for j in list2:
        if i in j and i != j:
            print j

这篇关于如何比较单词和字符串列表,然后使用python打印包含单词的完整字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆