繁体   English   中英

如何获取元素所在的列表?

[英]How do I get the list in which an element is in?

说我有两个清单:

L1 = [a, b, c, d]

L2 = [e, f, g, h]

字母可以是任何类型(它没有区别)。

有没有办法问Python:“哪个列表( L1和/或L2 )包含元素'a'(或任何其他元素),并让它返回该列表的名称?

为了实现这一点,更好的数据结构将使用dict 例如:

my_list_dict = {
    'L1': ['a', 'b', 'c', 'd'],
    'L2': ['e', 'f', 'g', 'h']
}

然后,您可以创建自定义函数来实现以下任务:

def find_key(c):
    for k, v in my_list_dict.items():
        if c in v:
            return k
    else:
        raise Exception("value '{}' not found'.format(c))

样品运行:

>>> find_key('c')
'L1'
>>> find_key('g')
'L2'

检查使用:

if 'a' in l1:
    print "element in l1" #or do whatever with the name you want
elif 'a' in l2:
    print "element in l2"
else:
    print "not in any list"

或使用如下功能:

def ret_name(c,l1,l2):
    if c in l1:
        return 1
    elif c in l2:
        return 2
    else:
        return 0
x=ret_name('a',l1,l2)
#and check if x=1 or x=2 or x=0 and you got your ans.

鉴于我们仅限于L1L2 ,这将做到这一点。

def contains(elem):
    return 'L1' if elem in L1 else 'L2'

为了灵活性,您可以将列表作为元组(list object, list name in string)传递(list object, list name in string)

>>> contains(a, [(L1, 'L1'), (L2, 'L2')])
>>> 'L1'

请注意,如果多个列表具有元素( elem ),该函数将返回基于顺序在tups提供的第一个列表。

def contains(elem, tups):
    for tup in tups:
        if elem in tup[0]: // list object
            return tup[1]  // list name

    return 'Not found'

虽然不鼓励,但如果通过globals()过滤将它们定义为程序中的变量,则可以动态获取列表的名称。

L1 = ['a', 'b', 'c', 'd']
L2 = ['e', 'f', 'g', 'h']

has_a = [k for k, l in globals().items() if isinstance(l, list) and 'a' in l]

print(has_a)
# ['L1']

这是我的解决方案,我发现它非常好:)

L1,L2 = ['a', 'b', 'c', 'd'],['e','f','g','h']
n = input('Enter a letter: ')
while True:
      if n in L1:
            print('Letter %s is contained inside L1 list!' %(n))
            break
      else:
            print('Letter %s is contained inside L2 list!' %(n))
            break

我希望它有助于快乐编码!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM