2016-12-01 32 views
2

說我有兩個列表:如何獲取元素所在的列表?

L1 = [a, b, c, d] 

L2 = [e, f, g, h] 

其中字母可以是任何類型的(它不會有所作爲)。

有沒有辦法問的Python:「哪個列表(L1和/或L2)包含元素a(或任何其他元素),並將它返回一個列表的名稱

+1

您的意思是實際上是否獲得了用戶聲明的'L1'或'L2'的名稱?如果是這樣,這在Python中是不可能的,因爲它缺乏這種類型的內省。如果你想要一個名稱和一些數據之間的映射,使用'dict' ... – dawg

回答

5

爲了達到這個目的,更好的數據結構將使用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' 
1

檢查?使用:

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. 
1

這也給我們僅限於L1L2

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

爲了靈活性,您可以將列表作爲元組列表(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' 
1

雖然不鼓勵,你可以動態獲取名稱如果通過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'] 
0

這是我的解決方案,我覺得這是相當不錯的:)

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 

我希望它能幫助編碼快樂!