2016-11-24 179 views
0

我有字符串'列'列表和相應的數據結果'數據'。 如何迭代數據並檢查我的變量是否與數據列表中的值具有相同的值?將變量匹配到基於變量名稱的列表

columns = ["username", "email", "admin", "alive"] 
data = ("john", "[email protected]", "True", "True") 

username = "john" 
email = "[email protected]" 
admin = False 
alive = True 

我希望得到這樣的輸出:["same", "different", "different", "same"]

回答

0

原來,我正在尋找簡單的eval()。

那麼簡單:

for i in data: 
    if i == eval(columns[data.index(i)]): 
    print("it's the same") 

的伎倆

0
data = ("john", "[email protected]", "True", "True") 
# create a dict with key and values 
# its about readability 
input_data = {"username":"john", 
       "email" :"[email protected]", 
       "admin" : False, 
       "alive" : True} 

match_list = {} 

for expected, (k,v) in zip(data, input_data.items()): 
    if expected != str(v): 
    match_list[k] = "different" 
    else: 
    match_list[k] = "same" 

for k,v in match_list.items(): 
    print (k,v) 

#your expected answer ["same", "different", "different", "same"] 
#is ok but not really useful.... 
#now you will get a key for your diff 

username same 
email different 
alive same 
admin different 
+0

thx!但在你的情況下,你只是比較兩個很好地相互配合的列表/字典。我的情況是我的代碼中有變量,並且我想根據'列'來請求這些變量。 '列'可以改變,用戶可以添加另一列,所以我想自動從我的代碼請求另一個變量 – tmdag

1

試試這個,

data = ("john", "[email protected]", True, True) 
check_list = [username,email,admin,alive] 
output = ['same' if i == j else 'diffrent' for i,j in zip(data,check_list)] 

輸出

[ '同',「不同勢','不同','相同']

+0

謝謝!這是假設check_list不是字符串列表,而是對變量的引用。使用'check_list = [「username」,「email」,「admin」,「alive」]'做任何可能性? – tmdag

0

如果你能避免這樣做,你應該。如果你無法避免它,你可以查找的名字變量的值在locals()

您的代碼:

columns = ["username", "email", "admin", "alive"] 
data = ("john", "[email protected]", "True", "True") 

username = "john" 
email = "[email protected]" 
admin = False 
alive = True 

要得到你想要的輸出:

['same' if str(i) == str(locals()[j]) else 'different' for i,j in zip(data, columns)] 

[ 'same','different','different','same']

對0123需要,因爲"True"True不一樣。