嵌套 list/dictionary 理解如何添加缺失的元素

nested list/dictionary comprehensions how to add a missing element

我需要在我的输出中添加一个天气字符串,我该怎么做?

weather_data_train = list()

for j in range(0,len(weather_sents_train)):
    weather_tokens = weather_sents_train[j].split()
    weather_dict = {}
    for key in weather_tokens:
        weather_dict[key] = True
    weather_data_train.append(weather_dict)

我得到的输出

[{'today': True, 'it': True, 'is': True, 'raining': True}, 
{'looking': True, 'cloudy': True, 'today': True}, 
{'it': True, 'is': True, 'nice': True, 'weather': True}]

我想要得到的输出

[({'today': True, 'it': True, 'is': True, 'raining': True}, 'weather'),
({'looking': True, 'cloudy': True, 'today': True}, 'weather'),
({'it': True, 'is': True, 'nice': True, 'weather': True}, 'weather')]

您可以将字典包含在元组中,'weather' 作为第二项。

变化:

weather_data_train.append(weather_dict)

至:

weather_data_train.append((weather_dict, 'weather'))

或者,您可以使用列表理解重写代码:

weather_data_train = [(dict.fromkeys(s.split(), True), 'weather') for s in weather_sents_train]