我试图用字典中的值替换列表(在所有相关子列表中)中的值,但无法使其正常工作。在
词典的内容/细节如下:
dictionary = dict(zip(gtincodes, currentstockvalues))
字典包含GTIN代码和currentstock值对。因此,12121212(GTIN)对应于值(currentstockvalue)1,12345670对应于值(currentstockvalue)0。在
我现在需要查找从文件中读入的列表NEWDETAILS。列表本质上是一个列表列表。打印newdetails(列表)时,输出为:
^{pr2}$需要做什么:
我想用字典更新和替换列表中的值(以及列表中所有相关的子列表)。因此,对于字典中的每个GTIN(key),每个子列表中的第3个索引(对应的GTIN)需要用字典中的值(currentstockvalue)更新。在
在上面的例子中,对于子列表1,子列表(whcih当前为5)的索引[03]需要更新为2…(或者字典中该GTIN的值是什么)。第二个子列表也需要这样做。在
到目前为止,我掌握的代码是:
^{3}$上面显示的只是生成两个独立的子列表并打印它们。它不是在进行替换。在
['12345670', 'Iphone 9.0', '500', '5', '3', '5']
['12121212', 'Samsung Laptop', '900', '5', '3', '5']
我的问题是:
如何修改上面的代码以查找每个子列表的字典(匹配索引[0]),并将每个子列表的第4个元素(索引[03])替换为字典中对应GTIN的值?在
提前谢谢。在
更新
根据Alex p的建议(谢谢),我做了以下编辑:
for sub_list in newdetails:
sub_list[3] = dictionary.get(gtin), sub_list[3]
print(sub_list)
它提供了一个替换(元组)而不仅仅是单个值-如下所示:
['12345670', 'Iphone 9.0', '500', (1, '5'), '3', '5']
['12121212', 'Samsung Laptop', '900', (1, '5'), '3', '5']
字典的内容:
12121212 3
0 0
12345670 1
12121212是gtin,“3”是当前库存。 我想查找字典,如果在newdetails列表中找到对应的GTIN,我想用字典中的相应值替换newdetails列表中的第三个索引(第四个元素)。所以,对于12121212,5将替换为3。对于12345670,5替换为1。在
根据Moses K的建议进行更新
我试过了-谢谢-但是。。。。在
for sub_list in newdetails:
sub_list[3] = dictionary.get(int(sub_list[0]), sub_list[3])
print(sub_list)
输出仍然只是两个子列表(未更改)。在
['12345670', 'Iphone 9.0', '500', '5', '3', '5']
['12121212', 'Samsung Laptop', '900', '5', '3', '5']
更新#2-两者都转换为int
for sub_list in newdetails:
print("sublist3")
print(sub_list[3])
sub_list[3] = dictionary.get(int(sub_list[0]), (int(sub_list[3])))
print(sub_list)
仍在生产:
['12345670', 'Iphone 9.0', '500', 5, '3', '5']
['12121212', 'Samsung Laptop', '900', 5, '3', '5']
而不是(我想要的)是: ['12345670','Iphone 9.0','500',2,'3','5'] ['12121212','Samsung Laptop','900',1,'3','5']
每个子列表的索引0处的
GTIN
代码应该是您的字典键:如果字典中的代码是整数而不是字符串,则需要将它们转换为
^{pr2}$int
:相关问题 更多 >
编程相关推荐