使用%s更改列表的名称

时间:2011-02-16 19:32:48

标签: python list dictionary

有没有办法使用%s更改列表名称?这是一个例子:

dict1[key]=value

for x in dict1.keys():
    %s %(x)profile=[]
    if dict1[x]=1:
        %s %(x)profile.append('yes')

此代码不起作用,但我正在寻找能够为{n}列表提供的内容,x中每个dict1.keys()一个。

3 个答案:

答案 0 :(得分:4)

简答:不。

答案很长:不,你不能做到这一点,但如果你对你的意图更清楚一点(用你的伪代码很难说你想要做什么),肯定有一种方法你你可以做你需要做的事情,即使你不能做尝试做什么

简短而危险的答案:其实是的,你可以,但不是你通常不应该

修改以获取更新后的评论

因此,您不想使用专门命名的列表,而是使用另一个字典:

new_dict = {}
for key in dict1.keys()
    new_key = "%sprofile" % key
    if dict1[key] == 1:   # note your = is actually a SyntaxError
        new_dict[new_key] = ['yes']
    else:
        new_dict[new_key] = []

如果原始字典的值为原始字典"yes",则会生成一个名为“(键)配置文件”的新字典,并且每个关联的值都是1的列表键或空列表。

答案 1 :(得分:0)

dict1 = {'a':0, 'b':0, 'c':1}

profile = { k:(['yes'] if v==1 else []) for k,v in dict1.iteritems() }

print profile
>>> {'a': [], 'b': [], 'c': ['yes']}

答案 2 :(得分:0)

这对你有帮助吗? :

dic = { 1:['a','h','uu'] , 3:['zer','rty'] , 4:['hj','125','qsd'] }

print 'BEFORE LOOP :\n\nglobals()==',globals()
print
print "keys of globals() not written __xxx__ :",' , '.join(u for u in globals() if not u.startswith('__'))
print '\n-----------------------------------------------------------------\nDURING LOOP :\n'
for x in dic:
    print 'x==',x
    globals()['L'+str(x)+'profile'] = dic[x]
    print 'keys of globals() not written __xxx__ :',' , '.join(u for u in globals() if not u.startswith('__'))

print '\n-----------------------------------------------------------------\nAFTER LOOP :\n'
print 'keys of globals() not written __xxx__ :',' , '.join(u for u in globals() if not u.startswith('__'))
print
for li in (L1profile,L3profile,L4profile):
    print 'li==',li

结果

BEFORE LOOP :

globals()== {'__builtins__': <module '__builtin__' (built-in)>, '__package__': None, '__name__': '__main__', 'dic': {1: ['a', 'h', 'uu'], 3: ['zer', 'rty'], 4: ['hj', '125', 'qsd']}, '__doc__': None}

keys of globals() not written __xxx__ : dic

-----------------------------------------------------------------
DURING LOOP :

x== 1
keys of globals() not written __xxx__ : L1profile , x , dic
x== 3
keys of globals() not written __xxx__ : L1profile , L3profile , x , dic
x== 4
keys of globals() not written __xxx__ : L1profile , L3profile , x , dic , L4profile

-----------------------------------------------------------------
AFTER LOOP :

keys of globals() not written __xxx__ : L1profile , L3profile , x , dic , L4profile

li== ['a', 'h', 'uu']
li== ['zer', 'rty']
li== ['hj', '125', 'qsd']

由于对象的名称不能以数字字符开头,因此系统地将“L”作为创建名称的第一个字母。