将变量匹配到基于变量名

时间:2016-11-24 11:50:26

标签: python

我有字符串'列'列表和相应的数据结果'数据'。 如何迭代数据并检查我的变量是否与数据列表中的值具有相同的值?

columns = ["username", "email", "admin", "alive"]
data = ("john", "john@snow.com", "True", "True")

username = "john"
email = "different@email.com"
admin = False
alive = True

我希望获得如下输出:["same", "different", "different", "same"]

4 个答案:

答案 0 :(得分:1)

试试这个,

df['e'] = df.d.sub(df.d.shift(), fill_value=0).astype(int)
print (df)
   a  b  c  d  e
0  9  3  3  0  0
1  3  9  5  1  1
2  1  7  5  6  5
3  8  0  1  7  1

<强>输出

  

['same','diffrent','diffrent','same']

答案 1 :(得分:0)

data = ("john", "john@snow.com", "True", "True")
# create a dict with key and values
# its about readability
input_data = {"username":"john",
              "email" :"different@email.com",
              "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

答案 2 :(得分:0)

事实证明我正在寻找简单的eval()。

这么简单:

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

做了这个伎俩

答案 3 :(得分:0)

如果你可以避免这样做,你应该。如果无法避免,可以在locals()

中按名称查找变量值

您的代码:

columns = ["username", "email", "admin", "alive"]
data = ("john", "john@snow.com", "True", "True")

username = "john"
email = "different@email.com"
admin = False
alive = True

获得所需的输出:

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

['相同','不同','不同','相同']

需要拨打str,因为"True"True不一样。