[英]How to output all first elements from all keys of a dictionary of lists of tuples?
我的字典my_emotions
一個片段如下所示:
{'art': [(2135, ['anticipation', 'joy', 'sadness', 'surprise'])],
'bad': [(7542, ['anger', 'disgust', 'fear', 'sadness'])],
'beautiful': [(4000, ['joy']), (4425, ['joy'])],
'boy': [(777, ['disgust']), (2634, ['disgust']), (4442, ['disgust'])],
'ceremony': [(2948, ['joy', 'surprise'])],
'child': [(4263, ['anticipation', 'joy'])],
'detention': [(745, ['sadness']),
(3461, ['sadness']),
(3779, ['sadness']),
(4602, ['sadness'])],...]}
我的目標是將每個鍵中出現的每個元組的所有第一個數字輸出到列表中。
到目前為止,我已經嘗試過了:
for key in sorted(my_emotions.keys()):
auto_emotion_indices = [].append(my_emotions[key][0][0])
但它輸出None
。
我嘗試使用以下命令打印輸出以查看得到的結果:
for key in sorted(my_emotions.keys()):
auto_emotion_indices = [].append(my_emotions[key][0][0])
它輸出我想要的字典部分(數字又稱為索引),但是當鍵多次出現時,僅輸出第一個。
例如,對於關鍵detention
:我只得到745
,而不是3461
, 3779
等..
所需的輸出將是:
my_list = [2135, 7542, 4000, 4425, 777, 2634, 4442, 2948, 4263, 745, 3461, 3779, 4602...]
我還應該添加些什么,以將這些數字的其余部分也包括在內?
提前致謝!
將my_emotions定義為:
my_emotions = {'art': [(2135, ['anticipation', 'joy', 'sadness', 'surprise'])],
'bad': [(7542, ['anger', 'disgust', 'fear', 'sadness'])],
'beautiful': [(4000, ['joy']), (4425, ['joy'])],
'boy': [(777, ['disgust']), (2634, ['disgust']), (4442, ['disgust'])],
'ceremony': [(2948, ['joy', 'surprise'])],
'child': [(4263, ['anticipation', 'joy'])],
'detention': [(745, ['sadness']),
(3461, ['sadness']),
(3779, ['sadness']),
(4602, ['sadness'])]}
此pythonic行將達到目的:
my_list = [number for emotion in sorted(my_emotions.keys()) for number, _ in my_emotions[emotion]]
一種較少使用pythonic的方法是使用兩個for循環來實現:
my_list = []
for emotion in sorted(my_emotions.keys()):
for number, _ in my_emotions[emotion]:
my_list.append(number)
如果要檢查要添加的內容,只需在內部循環中插入一條打印語句即可。 在這兩種情況下, 輸出均為:
[2135, 7542, 4000, 4425, 777, 2634, 4442, 2948, 4263, 745, 3461, 3779, 4602]
auto_emotion_indices = []
for keys in sorted(my_emotions.keys()):
for item in my_emotions[keys]:
auto_emotion_indices.append(item[0])
print(auto_emotion_indices)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.