![](/img/trans.png)
[英]How do I print a list of lists where the inner lists contain both strings and lists of strings?
[英]converting a list of lists to a dictionary where where the lists inside the list contain two strings
我有一個列表列表,其中列表中的列表包含兩個字符串。 我試圖將它們映射到字典中,其中鍵是列表中的第一個字符串,值是列表中的第二個字符串。
IE。 [[a,b],[c,d],[e,f]] 變成 {a:b,c:d,e:f}
但是我的代碼遇到錯誤:“列表索引必須是整數或切片,而不是 str”
idtoname = {}
for x in csv_data:
idtoname[csv_data[x[0]]] = csv_data[x[1]]
其中 csv_data 是列表列表。
idtoname = {}
for x in csv_data:
idtoname[x[0]] = x[1]
在循環中 x 已經是 csv_data 的一個元素。
您可以使用序列解包使表達式更具可讀性:
csv_data = [['a','b'],['c','d'],['e','f']]
idtoname = {}
for a, b in csv_data:
idtoname[a] = b
# idtoname = {'a': 'b', 'c': 'd', 'e': 'f'}
您可以在列表列表中調用dict()
:
>>> x = [['a', 'b'], ['c', 'd'], ['e', 'f']]
>>> dict(x)
{'a': 'b', 'c': 'd', 'e': 'f'}
將idtoname[csv_data[x[0]]] = x[1]
行更改為idtoname[csv_data[x[0]]] = x[1]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.