2011-02-16 90 views
0

的名字有没有办法来改变使用%s列表的名称?这里有一个例子:用%s更改列表

dict1[key]=value 

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

此代码没有工作,但我正在寻找的东西,这将使我“N”名单,每一个xdict1.keys()

+0

等待,笏?你是怎么想出来的?这是** **字符串格式化。 – delnan 2011-02-16 20:18:35

+0

你有没有看到我的答案吗? – eyquem 2011-02-18 00:10:22

回答

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对原始密钥,或一个空列表。

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']} 
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”开始被置于系统作为创建的名称的第一个字母。