Python 如何向字典中的列表添加索引
我这里有一本字典:Python 如何向字典中的列表添加索引,python,dictionary,Python,Dictionary,我这里有一本字典: dict = {'A':['1','1','1','1','1'], 'B':['2','2'], 'C':['3','3','3','3']} 获得以下结果的必要过程是什么 dict = {'A':['1_01','1_02','1_03','1_04','1_05'], 'B':['2_01','2_02'], 'C':['3_01','3_02','3_03','3_04']} 我学习python已经有一段时间了,但字典对我来说是一种新的东西。正如其他人提到的,不要
dict = {'A':['1','1','1','1','1'], 'B':['2','2'], 'C':['3','3','3','3']}
获得以下结果的必要过程是什么
dict = {'A':['1_01','1_02','1_03','1_04','1_05'], 'B':['2_01','2_02'], 'C':['3_01','3_02','3_03','3_04']}
我学习python已经有一段时间了,但字典对我来说是一种新的东西。正如其他人提到的,不要使用内置关键字作为变量名,例如
dict
。我保留它是为了你的简单
这可能是最具python风格的方法(一行代码):
您还可以遍历每个字典项,然后遍历每个列表项并手动更改列表名称,如下所示:
for key,value in dict.items():
for cnt,x in enumerate(value):
dict[key][cnt] = x+"_0"+str(cnt+1)
此外,正如其他一些人所提到的,如果您希望将大于10的数字保存为1_10而不是1_010,您可以在列表中添加if/else语句
dict = {key:[x+"_0"+str(cnt+1) if cnt+1 < 10 else x+"_"+str(cnt+1) for cnt,x in enumerate(value)] for key,value in dict.items()}
dict={key:[x+“_0”+str(cnt+1)如果cnt+1<10,则cnt为x+“_”+str(cnt+1),枚举(值)中的x为key,dict.items()中的值为}
使用枚举
迭代列表,跟踪索引:
d = {'A':['1','1','1','1','1'], 'B':['2','2'], 'C':['3','3','3','3']}
newd = {}
for k, v in d.items():
newd[k] = [f'{x}_0{i}' for i, x in enumerate(v, 1)]
print(newd)
还有词典理解:
d = {k: [f'{x}_0{i}' for i, x in enumerate(v, 1)] for k, v in d.items()}
注意:不要将字典命名为dict
,因为它会隐藏内置的
adict = {'A':['1','1','1','1','1'], 'B':['2','2'], 'C':['3','3','3','3'], 'D': '23454'}
newdict = {}
for i,v in adict.items():
if isinstance(v, list):
count = 0
for e in v:
count += 1
e += '_0' + str(count)
newdict[i] = newdict.get(i, [e]) + [e]
else:
newdict[i] = newdict.get(i, v)
print (newdict)
#{'A': ['1_01', '1_01', '1_02', '1_03', '1_04', '1_05'], 'B': ['2_01', '2_01', '2_02'], 'C': ['3_01', '3_01', '3_02', '3_03', '3_04'], 'D': '23454'}
此解决方案将检查字典中的值是否为列表,然后再为其指定索引首先迭代键
然后循环你在键上得到的键,比如'A'
值是['1','1','1','1']
,然后我们可以在['1','1','1','1']处更改元素。
enumerate()
帮助您在索引上迭代,然后根据您的预期输出将索引从零开始向索引添加1。由于您希望在每次计数之前都有尾随的0
,因此我们执行了“%02d%”(索引+1)
像这样:
dict = {'A':['1','1','1','1','1'], 'B':['2','2'], 'C':['3','3','3','3']}
for i in dict.keys(): #iterate on keys
for index,val in enumerate(dict[i]): #took value as we have key in i
element='%02d'% (index+1) #add trailing 0 we converted 1 to int 01
dict[i][index]=val+"_"+ str(element) #assign new value with converting integer to string
print(dict)
输出:
{'A':['1_01','1_02','1_03','1_04','1_05','C':['3_01','3_02','3_03','3_04'],'B':['2_01','2_02']
你可以使用口述:
d= {'A':['1','1','1','1','1'], 'B':['2','2'], 'C':['3','3','3','3']}
{x:[j + '_'+ '{:02}'.format(i+1) for i,j in enumerate(y)] for x,y in d.items()}
from itertools import starmap
d = {
'A': ['1', '1', '1', '1', '1'],
'B': ['2', '2'],
'C': ['3', '3', '3', '3']
}
f = lambda x, y: '%s_%02d' % (y, x)
print({k: list(starmap(f, enumerate(v, 1))) for k, v in d.items()})
# {'A': ['1_01', '1_02', '1_03', '1_04', '1_05'], 'B': ['2_01', '2_02'], 'C': ['3_01', '3_02', '3_03', '3_04']}
将dict
视为与列表类似的另一种数据类型,您可以在其中为索引命名{“key”:“value”}
是此数据类型的通用格式,其中key用作索引。要遍历字典,请使用作为关键字,dict_name.items()中的值:
。您还应该查看dictionary上Python的文档。虽然这很简单,但从数据模型的角度来看,结果可能没有多大帮助。当项目数超过10时,您希望得到什么,得到'1-010'
,或者只是'1-10'
?注意。因为dict
是一种内置类型,您可能需要为变量使用其他名称。:-)如果物品数量超过10,得到'1-010'
?@jiaJimmy,是的。(假设这是OP想要的)。这是最清楚的答案!谢谢你的帮助!很高兴我能帮忙!:)如果这解决了您的问题,请将此标记为已回答,以便其他人可以轻松找到!!为了帮助学习,请花些时间解释你的答案。它如何以及为什么解决OP的问题?
from itertools import starmap
d = {
'A': ['1', '1', '1', '1', '1'],
'B': ['2', '2'],
'C': ['3', '3', '3', '3']
}
f = lambda x, y: '%s_%02d' % (y, x)
print({k: list(starmap(f, enumerate(v, 1))) for k, v in d.items()})
# {'A': ['1_01', '1_02', '1_03', '1_04', '1_05'], 'B': ['2_01', '2_02'], 'C': ['3_01', '3_02', '3_03', '3_04']}