如何从元组列表的字典的所有键中输出所有第一元素?

时间:2018-08-17 19:39:39

标签: python list dictionary 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,而不会得到34613779等...

所需的输出为:

my_list = [2135, 7542, 4000, 4425, 777, 2634, 4442, 2948, 4263, 745, 3461, 3779, 4602...]

我应该添加些什么,以便将这些数字的其余部分也包括在内?

谢谢!

2 个答案:

答案 0 :(得分:1)

将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]

答案 1 :(得分:-1)

    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)