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. If yes, I need to append a string to 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].
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:
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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.