有没有办法打印出变量代表而不是变量? 让我来说明一下这个想法:
E=[4,19,0,17,8]
G=[4,13,8,18,17]
F=[4,18,0,8,19]
D=[4,13,0,19,8]
lag = [E, G, F, D]
lcode = [4,19,0,17,8]
for i in lag:
if i == lcode:
print "This is", i
我想要印刷品说:“这是E”......而不是:“这是[4,19,0,17,8]”
答案 0 :(得分:4)
这是使用dict
items = {"E": [1, 2, 3, 4, 5], "G": [1, 12, 13, 15] }
search = 4
for key, values in items.iteritems():
if search in values:
print key
输出:E
答案 1 :(得分:0)
使用字典的想法。你可以这样做:
mydict = {"E":[4,19,0,17,8],"G":[4,13,8,18,17],"F":[4,18,0,8,19],"D":[4,13,0,19,8]}
for key,value in mydict.iteritems():
if value == lcode:
print "This is %s" %(i)
iteritems()将字典元素分解为键值对,例如key:value ::“E”:[4,19,0,17,8]。
如果您要搜索所有列表中包含给定element
的内容:
for key,value in mydict:
if element in value:
print "Element in %s " %(key)
因此,如果element为4,程序将打印:
Element in E
Element in G
Element in F
Element in D
答案 2 :(得分:0)
没有创建Dict,你可以试试这个
import sys
E=[4,19,0,17,8]
G=[4,13,8,18,17]
F=[4,18,0,8,19]
D=[4,13,0,19,8]
lcode = [4,19,0,17,8]
modname = globals()['__name__']
modobj = sys.modules[modname]
lag = ["E","G","F","D"]
for name in lag:
if lcode == getattr(modobj, name):
print name
输出:E