检查列表中的字符串是否存在于另一个嵌套列表中,并在嵌套列表中返回它的索引

时间:2018-04-07 10:09:06

标签: python string python-2.7 nested-lists

所以我有两个列表,一个普通列表,一个嵌套列表,

list1 = ['john','amal','joel','george']
list2 = [['john'],['jack','john','mary'],['howard','john'],['jude']]

我想检查list1中是否存在list1中的任何字符串,如果是,则返回list2中字符串的索引(在两个列表中)。 演示所需输出的示例代码如下所示:

out = [(ind,ind2) for ind,i in enumerate(list2) 
    for ind2,y in enumerate(i) if 'john' in y]
print out

它返回:[(0, 0), (1, 1), (2, 1)]

上面的代码确实输出了索引,但它仅限于我们手动输入的字符串。有可能像我上面解释的那样吗?任何帮助将不胜感激。(相当新的嵌套列表)。 谢谢!

4 个答案:

答案 0 :(得分:2)

list1 = ['john','amal','joel','george']
list2 = [['john'],['jack','john','mary'],['howard','john'],['jude']]

res = []
for i, m in enumerate(list2):    #Iterate list2 
    for j, n in enumerate(m):    #Iterate nested list
        if n in list1:           #Check if element in list1
            res.append((i, j))   #Append index. 
print res

<强>输出:

[(0, 0), (1, 1), (2, 1)]

答案 1 :(得分:2)

你可以简单地遍历list1:

list1 = ['john','amal','joel','george']
list2 = [['john'],['jack','john','mary'],['howard','john'],['jude']]

res = {}
for w in list1: # if list1 contains duplicates use set(list1) instead
    # create an empty list for the name of list1 and extend it by all finds or
    # extend it by None
    res.setdefault(w,[]).extend( [(ind,ind2) for 
              ind,i in enumerate(list2) for ind2,y in enumerate(i) if w in y] or [None] )

# print all results by name
for k in res:
    print k, res[k]

# print all dict
print res

输出:

amal [None]
joel [None]
john [(0, 0), (1, 1), (2, 1)]
george [None]

{'amal': [None], 'joel': [None], 'john': [(0, 0), (1, 1), (2, 1)], 'george': [None]}

我在这里使用了一个字典,所以你不会松开列表中的哪一个。

答案 2 :(得分:1)

您可以使用嵌套列表理解:

[(i, j) for i, l in enumerate(list2) for j, s in enumerate(l) if s in list1]
#[(0, 0), (1, 1), (2, 1)]

请注意,首先将list1转换为set效率更高:

set1 = set(list1)
[(i, j) for i, l in enumerate(list2) for j, s in enumerate(l) if s in set1]
#[(0, 0), (1, 1), (2, 1)]

答案 3 :(得分:1)

您还可以创建事件的字典:

list1 = ['john','amal','joel','george']
list2 = [['john'],['jack','john','mary'],['howard','john'],['jude']]
new_d = {i:[(c, d) for d, a in enumerate(list2) for c, g in enumerate(a) if g == i] for i in list1}

输出:

{'amal': [], 'joel': [], 'john': [(0, 0), (1, 1), (1, 2)], 'george': []}