繁体   English   中英

检查列表或字符串以查看是否存在另一个列表中的字符串

[英]Check list or strings to see if a string from another list is present

我在ListA中有一个字符串列表,我需要检查listA中的任何字符串是否在listB的第i个元素中。 如果是,我需要在listB后面附加一个字符串。

例如

ListA =  [['Chicago'], ['Rockford'], ['Aurora']]

ListB = [['Town', 'Population', 'ZipCode'], ['Chicago Heights', '250,000', '12345'], ['Dallas', '1,700,000', '23456']]

如果ListA中的任何字符串位于ListB [0-2] [0]中字符串的某个位置,则需要在ListB [0-2]的末尾附加另一个字符串。

输出将是

ListC = [['Town', 'Population', 'ZipCode','not illinois'], ['Chicago Heights', '250,000', '12345', Illinois], ['Dallas', '1,700,000', '23456','not Illinois']]

提前致谢!

我很确定您可以从这里更明智的数据结构中受益,例如dict ,但这基本上可以满足您的要求:

for x in ListB:
    for y in x:
        if any(s in y for [s] in ListA):
            x.append('Illinois')
            break
    else:
        x.append('not Illinois')

注意:此方法将就地改变ListB ,而不是创建一个新的ListC

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM