【问题标题】:How to create a list of values in a dictionary comprehension in Python如何在 Python 中的字典理解中创建值列表
【发布时间】:2018-03-30 22:47:29
【问题描述】:

举一个非常简单的例子,循环一个句子并创建一个映射{x:y}的字典,其中x是表示单词长度的键,y是句子中包含的单词列表x字母数量

输入:

mywords = "May your coffee be strong and your Monday be short"

预期输出:

{2: ['be', 'be'], 3: ['May', 'and'], 4: ['your', 'your'], 5: ['short'], 6: ['coffee', 'strong', 'Monday']}

这是一个创建值列表但每次都覆盖它的尝试:

{len(x):[x] for x in mywords.split()}
{2: ['be'], 3: ['and'], 4: ['your'], 5: ['short'], 6: ['Monday']}

在 Python 中是否可以在一行中做到这一点?

【问题讨论】:

    标签: python list dictionary dictionary-comprehension


    【解决方案1】:

    当然,你可以使用sorted + groupby,但看起来不太好。

    from itertools import groupby
    d = dict([(k, list(g)) for k, g in groupby(sorted(mywords.split(), key=len), key=len)])
    
    print(d)
    {2: ['be', 'be'],
     3: ['May', 'and'],
     4: ['your', 'your'],
     5: ['short'],
     6: ['coffee', 'strong', 'Monday']}
    

    P.S.,这是我的answer(使用我推荐的defaultdict)给original question

    【讨论】:

      【解决方案2】:

      不要试图把所有的东西都塞进一行,它是不可读的。这是一个简单易懂的解决方案,即使它需要几行代码:

      from collections import defaultdict
      
      mywords = "May your coffee be strong and your Monday be short"    
      ans = defaultdict(list)
      
      for word in mywords.split():
          ans[len(word)].append(word)
      

      【讨论】:

      • 我同意这是执行此操作的“正确方法”......但它显然违反了他的单行条件......
      • @JoranBeasley 供参考,这个问题源于another question,而我的answer正是这个。
      • @cᴏʟᴅsᴘᴇᴇᴅ 我想当他最初发布它时,他只是对你的回答进行了元分析。我希望在理解中做到这一点,我在另一个答案中看到了这个解决方案,但我在一行中尝试它 - 结果发现 1 班轮比预期的要混乱
      【解决方案3】:

      可以通过构建一个从 1 到单词最大长度的原始字符串来使用正则表达式,然后使用组并将它们的位置迭代为单词的大小。最后使用默认字典将组中的单词添加到字典中。

      text = "May your hot chocolate be delicious and sweet and your Monday be short"
      
      max_len=0
      for word in text.split():
          if len(word)>max_len: 
              max_len=len(word) 
      
      pattern=[]
      
      for index in range(1,max_len+1):
          index=str(index)
          pattern.append(r"(\b\w{"+"{index}".format(index=index)+r"}\b\s+)*")
      
      pattern=''.join(pattern)
      print(pattern)
      groups=re.findall(pattern,text)
      dict = defaultdict(set)
      for group in groups:
          for position,value in enumerate(group):
              if len(value)>0:
                   dict[position+1].add(value)
      
       print(dict)
      

      输出:

       defaultdict(<class 'set'>, {3: {'May ', 'hot ', 'and '}, 4: {'your '}, 9: {'delicious ', 'chocolate '}, 2: {'be '}, 5: {'sweet '}, 6: {'Monday '}})
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-03-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-14
        • 2017-08-14
        • 2018-08-04
        相关资源
        最近更新 更多