我想要這樣的回圈,但得到所有東西,而不僅僅是第一個。
from collections import OrderedDict
myList = OrderedDict(
{
'ID': ["1stID", "2ndID","3ndID"], 'ChannelID': ["1stChannel", "2ndChannel","3ndChannel"]
})
first_values = [v[0] for v in myList.values()]
print(first_values)
OUTPUT
['1stID', '1stChannel']
代替
['1stID', '1stChannel']
DESIRED OUTPUT:
['1stID', '1stChannel']
['2stID', '2stChannel']
['3stID', '3stChannel']
uj5u.com熱心網友回復:
您可以使用zip()組合兩個串列并獲取組合對,如下所示:
from collections import OrderedDict
myList = OrderedDict(
{
'ID': ["1stID", "2ndID", "3ndID"],
'ChannelID': ["1stChannel", "2ndChannel", "3ndChannel"]
})
pairs = zip(myList['ID'], myList['ChannelID'])
# list(pairs) -> [('1stID', '1stChannel'), ('2ndID', '2ndChannel'), ('3ndID', '3ndChannel')]
for pair in pairs:
print(list(pair))
結果:
['1stID', '1stChannel']
['2ndID', '2ndChannel']
['3ndID', '3ndChannel']
uj5u.com熱心網友回復:
其他方法(如果您不想使用鍵名):
from collections import OrderedDict
myList = OrderedDict(
{
"ID": ["1stID", "2ndID", "3ndID"],
"ChannelID": ["1stChannel", "2ndChannel", "3ndChannel"],
}
)
for a in zip(*myList.values()):
print(a) # or list(a) for lists instead of tuples
印刷:
('1stID', '1stChannel')
('2ndID', '2ndChannel')
('3ndID', '3ndChannel')
uj5u.com熱心網友回復:
您誤解了您正在構建的結構,因此您無法正確訪問它。
mylist 是一個 2 元素字典。每個元素都是長度為 3 的串列。除了位置之外,彼此的位置元素之間沒有任何聯系。
請參閱下面我如何提取和列印資料的代碼。
可能有一種慣用的方式在 python 中更干凈地做到這一點,但這有助于清楚地顯示結構。
from collections import OrderedDict
myList = OrderedDict(
{
'ID': ["1stID", "2ndID", "3ndID"],
'ChannelID': ["1stChannel", "2ndChannel", "3ndChannel"]
})
first_values = [v[0] for v in myList.values()]
print(first_values)
#
# print out the values of the objects in the list
for v in myList.values():
print(v)
# extract the two lists
vid, vchan = myList.values()
# print out the whole list in one statement
print("all of vid ", vid)
print("all of vchan ", vchan)
# print out the element of the lists position by position
for i in range(len(vid)):
print(i, "th list item ", vid[i], vchan[i])
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/429003.html
上一篇:按鍵排序嵌套字典作為字串日期?
