아래 샘플 코드 :
list_of_dict = list([{'id':1,'amt':1},{'id':2,'amt':20},{'id':3,'amt':30}])
def fooFunc(a,b):
rows = [] ## list object
for e in range(b):
new = a.copy()
new['amt'] = a['amt'] / b
rows.append(new) ## using append()
return rows
output=[]
for i in list_of_dict:
idnmbr = i['id']
if idnmbr == 2:
output.append(fooFunc(i,2))
elif idnmbr == 3:
output.append(fooFunc(i,3))
else:
output.append(i)
print(output)
산출:
[{'id': 1, 'amt': 1}, [{'id': 2, 'amt': 10.0}, {'id': 2, 'amt': 10.0}], [{'id': 3, 'amt': 10.0}, {'id': 3, 'amt': 10.0}, {'id': 3, 'amt': 10.0}]]
함수 호출에서 추가되는 [대괄호] 즉 [{ 'id': 2, 'amt': 10.0}, { 'id': 2, 'amt': 10.0}]을 제거하지 마십시오. 결과 / 행을 목록으로 반환합니다.
함수 호출 반환을 사전 개체로 변환하려고 시도했지만 결과가 예상과 다릅니다.
def fooFuncDict(a,b):
rows = {} ## dictionary object
for e in range(b):
new = a.copy()
new['amt'] = a['amt'] / b
rows.update(new) ## using update()
return rows
output=[]
for i in list_of_dict:
idnmbr = i['id']
if idnmbr == 2:
output.append(fooFuncDict(i,2))
elif idnmbr == 3:
output.append(fooFuncDict(i,3))
else:
output.append(i)
print(output)
산출:
[{'id': 1, 'amt': 1}, {'id': 2, 'amt': 10.0}, {'id': 3, 'amt': 10.0}]
나는 당신이 필요하다고 믿습니다 list.extend
전의:
output=[]
for i in list_of_dict:
idnmbr = i['id']
if idnmbr == 1:
output.append(i)
else:
output.extend(fooFunc(i,idnmbr))
print(output)
# [{'id': 1, 'amt': 1}, {'id': 2, 'amt': 10.0}, {'id': 2, 'amt': 10.0}, {'id': 3, 'amt': 10.0}, {'id': 3, 'amt': 10.0}, {'id': 3, 'amt': 10.0}]
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다