簡體   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