[英]How to output all first elements from all keys of a dictionary of lists of tuples?
A snippet from my dictionary my_emotions
looks like this: 我的字典
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'])],...]}
I am aiming to output all the first numbers of every tuple that occur in every key into a list. 我的目标是将每个键中出现的每个元组的所有第一个数字输出到列表中。
So far I've tried this: 到目前为止,我已经尝试过了:
for key in sorted(my_emotions.keys()):
auto_emotion_indices = [].append(my_emotions[key][0][0])
but it outputs None
. 但它输出
None
。
I tried printing the output to see what I'm getting, using: 我尝试使用以下命令打印输出以查看得到的结果:
for key in sorted(my_emotions.keys()):
auto_emotion_indices = [].append(my_emotions[key][0][0])
which outputs the part of the dictionary that I want (the numbers aka indices), but only the first ones when there's multiple occurances for a key. 它输出我想要的字典部分(数字又称为索引),但是当键多次出现时,仅输出第一个。
Eg for the key detention
: I only get 745
, but not 3461
, 3779
etc... 例如,对于关键
detention
:我只得到745
,而不是3461
, 3779
等..
A desired output would be: 所需的输出将是:
my_list = [2135, 7542, 4000, 4425, 777, 2634, 4442, 2948, 4263, 745, 3461, 3779, 4602...]
What should I add to also include the rest of those numbers into my list? 我还应该添加些什么,以将这些数字的其余部分也包括在内?
Thanks in advance! 提前致谢!
Defining my_emotions as: 将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'])]}
This pythonic line will do the trick: 此pythonic行将达到目的:
my_list = [number for emotion in sorted(my_emotions.keys()) for number, _ in my_emotions[emotion]]
A less pythonic way is to do it with two for loops: 一种较少使用pythonic的方法是使用两个for循环来实现:
my_list = []
for emotion in sorted(my_emotions.keys()):
for number, _ in my_emotions[emotion]:
my_list.append(number)
If you want to check what is being added just insert a print statement in the inner loop. 如果要检查要添加的内容,只需在内部循环中插入一条打印语句即可。 In both cases the output is:
在这两种情况下, 输出均为:
[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.