![](/img/trans.png)
[英]Python - Check if strings/initials in a list are present in another list
[英]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.