【问题标题】:Get first element of a string sublist as a dictionary key with a list of value in python获取字符串子列表的第一个元素作为字典键与python中的值列表
【发布时间】:2020-04-10 03:19:10
【问题描述】:

所以我有一个字符串列表。我需要将字符串的第一部分转换为字典中的键,并将剩余部分视为值。例如,列表是:

['We have a nice weekend','Hope you all well']

它应该返回:

{'We':['have','a','nice','weekend'],'Hope':['you','all','well']}

我的尝试如下:

dict1 = {}   
dict1 = {item[0]:item[1:] for item in List1}
return dict1

但这给了我一个结果:

{'W':'e have a nice weekend','H':'ope you all well'

如何解决?提前致谢。

【问题讨论】:

    标签: python python-3.x string list dictionary


    【解决方案1】:

    你可以试试这个。

    lines=['We have a nice weekend','Hope you all well']
    d={}
    
    for line in lines:
        k,*v=line.split()
        d[k]=v
    d
    # {'We': ['have', 'a', 'nice', 'weekend'], 'Hope': ['you', 'all', 'well']}
    

    【讨论】:

      【解决方案2】:

      试试这个:

      x = ['We have a nice weekend','Hope you all well']
      

      然后:

      y = {s[0]:s[1:] for s in (p.split() for p in x)}
      

      那么y就是:

      {'We': ['have', 'a', 'nice', 'weekend'],
       'Hope': ['you', 'all', 'well']}
      

      【讨论】:

        【解决方案3】:

        尝试以下方法:

        list1 = ['We have a nice weekend', 'Hope you all well']
        
        # convert a string into list of words separated by a space
        list1 = [item.split(' ') for item in list1]
        print(list1) # [['We', 'have', 'a', 'nice', 'weekend'], ['Hope', 'you', 'all', 'well']]
        
        dict1 = {item[0]: item[1:] for item in list1}
        print(dict1) # {'We': ['have', 'a', 'nice', 'weekend'], 'Hope': ['you', 'all', 'well']}
        

        【讨论】:

        • 谢谢,但我尝试了另一个示例,它在字典中的每个值之前都有 '' '' 的子列表
        【解决方案4】:

        替换你的第二行:

        dict1 = {item[0]:item[1:] for item in List1}
        

        用这个:

        dict1 = {item.split()[0]:' '.join(item.split()[1:]) for item in List1}
        

        【讨论】:

        • 此解决方案不必要地将每个字符串拆分两次。它应该将每个字符串拆分一次。
        • @TomKarzes 我同意你的评论。您的解决方案是将一个拆分存储在变量中的更好方法。
        【解决方案5】:

        您可以使用 map 来拆分列表中的每个字符串并解包以将第一个单词与其余单词分开:

        strings = ['We have a nice weekend','Hope you all well']
        result  = { k:v for k,*v in map(str.split,strings) }
        

        输出:

        print(result)
        
        {'We': ['have', 'a', 'nice', 'weekend'], 'Hope': ['you', 'all', 'well']}
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2023-03-10
          • 2012-03-03
          • 2011-10-29
          • 1970-01-01
          • 2019-04-24
          • 2016-09-03
          • 1970-01-01
          相关资源
          最近更新 更多