2016-03-23 14 views
3

Burada iç içe geçmiş listelerin sözlüğüne bir değer eklemek istiyorum. Bu, denedim ettiğimiIç içe geçmiş listelerin dict içine bir değer ekleme

company_ids = [1,2,3] 
seller_ids = [[0, False, { u'company_id': 4}]] 
result = [] 
for company in company_ids: 
    for i in xrange(0, len(seller_ids)): 
     seller_ids[i][2]['company_id'] = company 
     result.append(seller_ids[i]) 
print result 

Bu

[[0, False, {u'company_id': 3}], 
[0, False, {u'company_id': 3}], 
[0, False, {u'company_id': 3}]] 

Ama bu bekliyorum,

[[0, False, {u'company_id': 1}], 
[0, False, {u'company_id': 2}], 
[0, False, {u'company_id': 3}]] 

alıyorum olduğunu Lütfen bana yardım et e bu. Şimdiden teşekkürler ...

cevap

2

Değiştirmek istediğiniz girişin bir kopyasını satıcı_varlıkları içinde oluşturmanız gerekir. Niemmi'nin de dediği gibi, her seferinde aynı girişi manipüle edersiniz.

from copy import deepcopy 

company_ids = [1,2,3] 
seller_ids = [[0, False, { u'company_id': 4}]] 
result = [] 
for company in company_ids: 
    for i in xrange(0, len(seller_ids)): 
     mycopy = deepcopy(seller_ids[i]) 
     mycopy[2]['company_id'] = company 
     result.append(mycopy) 

print result 
1

Bu, [0, False, { u'company_id': 4}]'u her seferinde her seferinde değiştirip eklediğinizde, son değişiklikle aynı listeye üç başvuru içerecektir.

İlgili konular