的名字有沒有辦法來改變使用%s
列表的名稱?這裏有一個例子:用%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()
。
的名字有沒有辦法來改變使用%s
列表的名稱?這裏有一個例子:用%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()
。
簡短的回答:沒有。
長答案:不,你不能做到這一點,但如果你對你的意圖更清楚一點(很難用你的僞代碼告訴你想要做什麼),肯定有辦法你可以做你需要,甚至做雖然你不能做什麼你試圖做
短而危險的答案:其實是你那種可以,但沒有你一般不應
編輯爲您的更新評論
所以不是有專門命名列表,你想用的是另一種解釋:
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
對原始密鑰,或一個空列表。
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']}
這是否幫助你嗎? :
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」開始被置於系統作爲創建的名稱的第一個字母。
等待,笏?你是怎麼想出來的?這是** **字符串格式化。 – delnan 2011-02-16 20:18:35
你有沒有看到我的答案嗎? – eyquem 2011-02-18 00:10:22