python如何在二维列表中查找元素?

例如现在有两个list
list1=[[u'https://www.ubisoft.com.cn', u'122.225.217.248', u'443'], [u'www.ubisoft.com.cn', u'122.225.217.238', u'80'], [u'https://source.ubisoft.com.cn', u'117.50.99.193', u'443'], [u'source.ubisoft.com.cn', u'117.50.99.193', u'80'], [u'ubisoft.com.cn', u'203.107.45.167', u'80'], [u'tigeryear.ubisoft.com.cn', u'183.6.231.199', u'80'], [u'https://tigeryear.ubisoft.com.cn', u'36.102.212.85', u'443']]list2=[u'www.ubisoft.com.cn', u'source.ubisoft.com.cn', u'tigeryear.ubisoft.com.cn', 'test.ubisoft.com.cn']
list2中的元素不一定在list1中存在,
现在想实现一个功能,遍历list2中的元素,然后去list1中查找,如果存在,则返回list1中的ip,如果不存在则输出该元素
我想用for去实现,可是输出结果一直有问题,大佬们能给指点一下吗
list1=[[u'https://www.ubisoft.com.cn', u'122.225.217.248', u'443'], [u'www.ubisoft.com.cn', u'122.225.217.238', u'80'], [u'https://source.ubisoft.com.cn', u'117.50.99.193', u'443'], [u'source.ubisoft.com.cn', u'117.50.99.193', u'80'], [u'ubisoft.com.cn', u'203.107.45.167', u'80'], [u'tigeryear.ubisoft.com.cn', u'183.6.231.199', u'80'], [u'https://tigeryear.ubisoft.com.cn', u'36.102.212.85', u'443']]list2=[u'www.ubisoft.com.cn', u'source.ubisoft.com.cn', u'tigeryear.ubisoft.com.cn', 'test.ubisoft.com.cn']
for i in list2:
    for j in list1:
        if i in j[0]:
            print j[1]
        else:
            print i
预想的结果应该是输出3个ip和一个域名,但实际上会输出很多域名(也就是print i 执行了很多次),求大神指点一下如何去处理这种语句
回答:
问题在于第二层for循环遍历时,当找到元素时,并没有及时跳出当前循环。
for i in list2:
    exist_domain = False
    # TODO: 这里 in ? 还是 == ?
    for j in list1:
        if i == j[0]:
            print(j[1])
            # 设置标识位,当找到了 就不再打印域名i 而是打印IP地址j[1]
            exist_domain = True
            # 找到了 直接跳出循环
            break
    # 当没有找到的情况,打印域名i
    if not exist_domain:
        print(i)
另外,推荐使用Python3。
另外,你还可以将list1转换成map来处理。更方便一些,你可以试试.
python">map1 = {    u'https://www.ubisoft.com.cn': [u'https://www.ubisoft.com.cn', u'122.225.217.248', u'443']
}
# -*- coding: UTF-8 -*-__author__ = 'lpe234'
list1 = [[u'https://www.ubisoft.com.cn', u'122.225.217.248', u'443'],
         [u'www.ubisoft.com.cn', u'122.225.217.238', u'80'],
         [u'https://source.ubisoft.com.cn', u'117.50.99.193', u'443'],
         [u'source.ubisoft.com.cn', u'117.50.99.193', u'80'],
         [u'ubisoft.com.cn', u'203.107.45.167', u'80'],
         [u'tigeryear.ubisoft.com.cn', u'183.6.231.199', u'80'],
         [u'https://tigeryear.ubisoft.com.cn', u'36.102.212.85', u'443']]
list2 = [u'www.ubisoft.com.cn', u'source.ubisoft.com.cn', u'tigeryear.ubisoft.com.cn', 'test.ubisoft.com.cn']
def find_domain(domain: str, domain_list: list) -> str:
    for dl in domain_list:
        if domain == dl[0]:
            # 当找到符合条件的, 直接返回
            return dl[1]
    # 执行到这步, 说明没有符合条件的
    return domain
def main():
    for i in list2:
        d = find_domain(i, list1)
        print(d)
if __name__ == '__main__':
    main()
以上是 python如何在二维列表中查找元素? 的全部内容, 来源链接: utcz.com/p/938680.html

