python:for循环中字典列表中的字符串

2024-10-01 00:25:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一份文本清单如下:

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'}

Tags: the文本forismyblueavailableentry
2条回答

请阅读fromkeys()方法。该方法返回一个新字典,其中给定的元素序列作为字典的键

seq = "hello"
value = dict.fromkeys(seq, "world")
print(value)
# the output is {'h': 'world', 'e': 'world', 'l': 'world', 'o': 'world'}

基于字典生成器(https://python-reference.readthedocs.io/en/latest/docs/comprehensions/dict_comprehension.html)的解决方案:

print({entry:'analyzed' for entry in my_texts if len(entry.split()) > 2 and entry.split()[0] != 'apples'})

输出:

{'Citrus is beneficial': 'analyzed', 'the sky is blue': 'analyzed', 'the grass is green': 'analyzed'}

如果需要N个字典,每个字典中有1个元素,可以使用

for entry in my_texts:
    if len(entry.split()) > 2 and entry.split()[0] != 'apples':
        print({entry: 'analyzed'})

输出2:

{'Citrus is beneficial': 'analyzed'}
{'the sky is blue': 'analyzed'}
{'the grass is green': 'analyzed'}

相关问题 更多 >