[英]How can I get average of value in list of lists and add it to a dictionary
[英]How do you get at a value in a list of lists /replace it with a dictionary value?
我需要在列表列表中獲取值。 有問題的列表稱為“newdetails”。 它的內容如下
[['12345670', 'Iphone 9.0', '500', '5', '3', '5'], ['12121212', 'Samsung Laptop', '900', '5', '3', '5']]
我發現print(newdetails [0])打印出整個第一個列表。 然而,我需要的是獲得第一個列表的索引[0],即12345670.我還需要將索引03(兩個列表)替換為字典中的VALUE,這對應於第一個GTIN編號。
我到目前為止的代碼是:
for gtin,currentstock in dictionary.items():
if newdetails[0]==gtin:
newdetails[3]=currentstock
print("checking to see what newdetails[0] and [3] and [9] is")
print(newdetails[0])
print("or is it a matrix or a 2d array")
print(newdetails[0,3])
print("now will this work...print replacement list")
print(newdetails)
有人可以幫忙嗎?
更新:
謝謝你的建議。 我試過這個:(但它出現了錯誤)
for sub_list in newdetails:
sub_list[3] = dictionary(sub_list[3], sub_list[3])
print("sublist")
print(sub_list)
錯誤:sub_list [3] =字典(sub_list [3],sub_list [3])TypeError:'dict'對象不可調用
為了澄清,我所擁有的列表被稱為“newdetails” - 它內部有兩個列表(從文件中讀入)。 字典的名稱只是字典(現在),它有一個GTIN鍵和一個'currentstock'VALUE。 我希望字典中的GTIN鍵與BOTH列表中的相同GTIN值相對應,以更新索引3(當前顯示為5)。 字典中的值'currentstock',對應於GTIN編號。
在此先感謝有用的天才誰能幫我解決這個問題!
如果您有列表清單
data = [['12345670', 'Iphone 9.0', '500', '5', '3', '5'],
['12121212', 'Samsung Laptop', '900', '5', '3', '5']]
然后,當你發現data[0]
將返回列表中的第一個列表。 然后,如果您想再次使用第一個項目,那么data[0][0]
就是您所需要的。
要替換兩者的第三個索引,可以這樣做:
for row in data:
row[3] = 'foo'
對於多維數組,使用numpy庫。
在python中,只需使用嵌套列表索引:
>>> x = [['12345670', 'Iphone 9.0', '500', '5', '3', '5'], ['12121212', 'Samsung Laptop', '900', '5', '3', '5']]
>>> x[0]
['12345670', 'Iphone 9.0', '500', '5', '3', '5']
>>> x[0][0]
'12345670'
>>> x[0][3] = '600'
>>> x[0][3]
'600'
假設您有一個映射到問題中提到的子列表中相應元素的key
列表。 以下是實現該目標的示例代碼:
my_list = [['12345670', 'Iphone 9.0', '500', '5', '3', '5'], ['12121212', 'Samsung Laptop', '900', '5', '3', '5']]
my_key = ['item1', 'item2', 'item3', 'item4', 'item5', 'item6']
dict_list = [{k: v for k, v in zip(my_key, sub_list)} for sub_list in my_list]
# Value of "dict_list":
[{
'item2': 'Iphone 9.0',
'item3': '500',
'item6': '5',
'item4': '5',
'item5': '3',
'item1': '12345670'
},
{
'item2': 'Samsung Laptop',
'item3': '900',
'item6': '5',
'item4': '5',
'item5': '3',
'item1': '12121212'
}]
要了解有關此代碼如何工作的更多信息,請Dict Comprehension in Python
檢查zip()
和Dict Comprehension in Python
。
如果你想更新列的value
,讓我們說列表中第0
個索引的'item6',你可以這樣做:
dict_list[0]['item6'] = 'new value'
更新 :根據OP的評論
# my_gtin <-- GTIN dict
for sub_list in my_list:
sub_list[3] = my_gtin.get(sub_list[3], sub_list[3])
上面的代碼將根據my_gtin
dict中是否存在key
來更新sub_list
中第3
索引的條目。 否則sub_list
將具有相同的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.