[英]Check list or strings to see if a string from another list is present
I have a list of strings in ListA, and I need to check if any string from listA is in the ith element of listB. 我在ListA中有一个字符串列表,我需要检查listA中的任何字符串是否在listB的第i个元素中。 If yes, I need to append a string to listB.
如果是,我需要在listB后面附加一个字符串。
For example 例如
ListA = [['Chicago'], ['Rockford'], ['Aurora']]
ListB = [['Town', 'Population', 'ZipCode'], ['Chicago Heights', '250,000', '12345'], ['Dallas', '1,700,000', '23456']]
If any string in ListA, is at some point of the string in ListB[0-2][0], I need to append another string to end of the ListB[0-2]. 如果ListA中的任何字符串位于ListB [0-2] [0]中字符串的某个位置,则需要在ListB [0-2]的末尾附加另一个字符串。
The output would be 输出将是
ListC = [['Town', 'Population', 'ZipCode','not illinois'], ['Chicago Heights', '250,000', '12345', Illinois], ['Dallas', '1,700,000', '23456','not Illinois']]
Thanks in Advance! 提前致谢!
I'm pretty sure you could benefit from a more sensible data structure here, eg a dict
, but this basically does what you've asked: 我很确定您可以从这里更明智的数据结构中受益,例如
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')
Note: this method mutates ListB
in place, rather than creating a new ListC
. 注意:此方法将就地改变
ListB
,而不是创建一个新的ListC
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.