如何检查内部列表中是否存在某个项目,并在包含该项目的相应外部列表中获取该列表项目?

时间:2019-05-09 09:39:23

标签: python

我有一个这样的列表:

[[0, [2]], [1, [4]], [2, [0, 6]], [3, [3]], [4, [0, 6]]]

我想要这样的东西:

检查内部列表中是否存在2个(可以包含多个项目),然后获取对应的外部列表值(始终为1个)的值为0。

输入:

[[0, [2]], [1, [4]], [2, [0, 6]], [3, [3]], [4, [0, 6]]]

输出(一些示例):

Search for 2
2 was found with 0

Search for 0
0 was found with 2 and 4

Search for 3
3 was found with 3

3 个答案:

答案 0 :(得分:2)

您可以使用列表推导来检查子列表是否包含给定的数字,然后获取相应的外部列表值:

num = 0
out = [i[0] for i in l if num in i[1]]
'{} was found with {}'.format(num, ', '.join(map(str,out)))
# '0 was found with 2, 4'

或输入数字num=2

out = [i[0] for i in l if num in i[1]]
# '2 was found with 0'

以上答案假定内部列表始终位于第二位置。如果不是这种情况,您可以改为:

out = [i[0] for i in l if num in sorted(i, key=lambda x: isinstance(x, list))[1]]
'{} was found with {}'.format(num, ', '.join(map(str,out)))
# '0 was found with 2, 4'

答案 1 :(得分:1)

确切的输出结果

如果您希望输出与您所描述的完全相同:

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    from solution import *
  File "/home/codewarrior/solution.py", line 2
    return m = s[len(s/2)] if type(len(s)/2) is float else if                            
      s[int(len(s)/2)-1:int(len(s)/2)]             
           ^
 SyntaxError: invalid syntax
  

搜索0
  找到0和2和4

排序版本

如果您只需要了解为其找到搜索值的外部值:

values = [[0, [2]], [1, [4]], [2, [0, 6]], [3, [3]], [4, [0, 6]]]

search_value = 0
print(f"Search for {search_value}")

found = []
for outer, inner in values:
    if search_value in inner:
        found.append(outer)

if found:
    print(f"{search_value} was found with ", end="")
    print(*found, sep=" and ")
  

2和4

甚至更短的版本

用列表理解功能替换两个for循环,以实现一个简单的班轮:

values = [[0, [2]], [1, [4]], [2, [0, 6]], [3, [3]], [4, [0, 6]]]
search_value = 0

for outer, inner in values:
    if search_value in inner:
        print(outer, end=" and ")
  

2,4


使用Python values = [[0, [2]], [1, [4]], [2, [0, 6]], [3, [3]], [4, [0, 6]]] search_value = 0 print(*[outer for outer, inner in values if search_value in inner], sep=", ")

答案 2 :(得分:-1)

您可以从此列表创建字典,然后按字典中的项目进行迭代。

your_list = [[0, [2]], [1, [4]], [2, [0, 6]], [3, [3]], [4, [0, 6]]]
dictionary = dict(your_list)
# or just dictionary = dict([[0, [2]], [1, [4]], [2, [0, 6]], [3, [3]], [4, [0, 6]]])
for key, value in dictionary.items():
    if 2 in value:
        print(key)

当然,您可以将其包装为某些方法:

def some_fancy_name(dict, item):
    for key, val in dict.items():
        if item in val:
            return key