2016-11-24 109 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不一样。