Python 动态填充字典
我很想知道是否可以直接将一组值附加到字典中,而不首先将它们存储在列表中,就像我在下面的代码中所做的那样。我的想法是省略tempD、tempR和tempA变量Python 动态填充字典,python,loops,dictionary,Python,Loops,Dictionary,我很想知道是否可以直接将一组值附加到字典中,而不首先将它们存储在列表中,就像我在下面的代码中所做的那样。我的想法是省略tempD、tempR和tempA变量 getD = {} getR = {} getA = {} count = -1 for j in range(0, 180, 45): count += 1 getD[count] = {} getR[count] = {} getA[count] = {} tempD = [] t
getD = {}
getR = {}
getA = {}
count = -1
for j in range(0, 180, 45):
count += 1
getD[count] = {}
getR[count] = {}
getA[count] = {}
tempD = []
tempR = []
tempA = []
for k in range(len(lA)):
if (j <= lA[k] < j + step):
tempD.append(lD[k])
tempR.append(lR[k])
tempA.append(lA[k])
getD[count] = tempD
getR[count] = tempR
getA[count] = tempA
getD={}
getR={}
getA={}
计数=-1
对于范围(0、180、45)内的j:
计数+=1
getD[count]={}
getR[count]={}
getA[count]={}
tempD=[]
tempR=[]
坦帕=[]
对于范围内的k(len(lA)):
如果(j您可以使用defaultdict
,这样getD[count]
将以列表形式开始:
from collections import defaultdict
getD = defaultdict(list)
getR = defaultdict(list)
getA = defaultdict(list)
count = -1
for j in range(0, 180, 45):
count += 1
for k in range(len(lA)):
if (j <= lA[k] < j + step):
getD[count].append(lD[k])
getR[count].append(lR[k])
getA[count].append(lA[k])
从集合导入defaultdict
getD=defaultdict(列表)
getR=defaultdict(列表)
getA=defaultdict(列表)
计数=-1
对于范围(0、180、45)内的j:
计数+=1
对于范围内的k(len(lA)):
如果(j即使这不完全是你的问题:在你的情况下,使用列表理解可能是有益的:
getD = {}
getR = {}
getA = {}
for count, j in enumerate(range(0, 180, 45)):
aBound = j + step
getD[count] = [lD[k] for k, a in enumerate(lA) if j <= lD[k] and a < aBound]
getR[count] = [lR[k] for k, a in enumerate(lA) if j <= lR[k] and a < aBound]
getA[count] = [a for a in lA if j <= a and a < aBound]
getD={}
getR={}
getA={}
对于计数,枚举中的j(范围(0、180、45)):
富足=j+步进
getD[count]=[lD[k]对于k,a在枚举(lA)中如果j请描述上述程序允许的输入和预期的输出是什么。是的。最简单的方法是使用一个defaultdict(list)
,但只要键有一个列表值,就可以执行d[key]。追加(value)
为什么要初始化getD[count]
与{}
一起使用?您不想在此处列出一个列表吗?而且,您无论如何都要覆盖它,对吗?getD
应该是defaultdict
,然后getD[count]
是一个列表。其他的也一样