我有一份文本清单如下:
my_texts = ['apples are available', 'Citrus is beneficial', 'the sky is blue',
'the grass is green', 'not available', 'not possible']
我正在分析以下for循环中的文本,并希望将字符串转换为字典
for entry in [entry for entry in my_texts]:
if len(entry.split()) > 2:
if entry.split(' ', 1)[0] != 'apples':
print (dict.fromkeys(entry ,'analyzed'))
但是,当前输出与我期望的输出确实不同:
current_output = {'C': 'analyzed', 'i': 'analyzed', 't': 'analyzed', 'r': 'analyzed', 'u': 'analyzed', 's': 'analyzed', ' ': 'analyzed', 'b': 'analyzed', 'e': 'analyzed', 'n': 'analyzed', 'f': 'analyzed', 'c': 'analyzed', 'a': 'analyzed', 'l': 'analyzed'}
{'t': 'analyzed', 'h': 'analyzed', 'e': 'analyzed', ' ': 'analyzed', 's': 'analyzed', 'k': 'analyzed', 'y': 'analyzed', 'i': 'analyzed', 'b': 'analyzed', 'l': 'analyzed', 'u': 'analyzed'}
{'t': 'analyzed', 'h': 'analyzed', 'e': 'analyzed', ' ': 'analyzed', 'g': 'analyzed', 'r': 'analyzed', 'a': 'analyzed', 's': 'analyzed', 'i': 'analyzed', 'n': 'analyzed'}
而我期望的输出是:
desired_output ={'Citrus is beneficial': 'analyzed'}
{'the sky is blue': 'analyzed'}
{'the grass is green': 'analyzed'}
请阅读fromkeys()方法。该方法返回一个新字典,其中给定的元素序列作为字典的键
基于字典生成器(https://python-reference.readthedocs.io/en/latest/docs/comprehensions/dict_comprehension.html)的解决方案:
输出:
如果需要N个字典,每个字典中有1个元素,可以使用
输出2:
相关问题 更多 >
编程相关推荐