[英]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.