【问题标题】:Splitting list into dictionary based on value type根据值类型将列表拆分为字典
【发布时间】:2017-04-30 21:49:46
【问题描述】:

我有一个列表,其中包含一个单词后跟多个数字。有些用逗号分隔我的空间。我正在尝试使单词成为字典中的键,然后将每个数字拆分为一个单独的列表并将其存储为字典值。

输入:

my_list = ['word 1234 123 1', 'word 123 43 564', 'somethingelse 123,4124,56', etc...]

输出:

my_dict = {'word': ['1234', '123', '1'],
     'word': ['123', '43', '564'], 'somethingelse': '123', '4124', '56' ]}

到目前为止,我已经尝试过创建要删除的单词以及不同的正则表达式:

re.sub(r'([^\s\w]|_)+', '', str(my_list))

stopwords = ['word']
querywords = my_list.split()
resultwords = [word for word in querywords if word.lower() not in stopwords]
result = ' '.join(resultwords)

re.findall('\d+|\D+', my_list)

我写了这个方法在某些单词之前进行拆分:

def removeBeforeX(self, x, listIn, listOut):
        for item in listIn:
            if x in item:
                a,b = item.split(x)
                listOut.append(b)
            else:
                listOut.append(item)
        return listOut

我不一定需要单词作为键,因为键在字典中必须是唯一的,但我确实需要将数字分开,但将它们放在一个列表中。

【问题讨论】:

  • 你不能在同一个字典中有多个键word。
  • 不能在一个字典中多次使用相同的关键字。键必须是唯一的
  • 请告诉我们你尝试了什么,你的方法是什么,你遇到了什么困难?本社区不提供解决方案,我们为您寻找解决方案提供帮助。
  • dic 中可以有多个值名称但不能有多个键名称
  • 我尽可能少地提供信息,因为我想直截了当。我已经用我尝试过的方法更新了我的答案。

标签: python regex python-2.7


【解决方案1】:

有什么问题?

>>> import re
>>> my_dict={}
>>> my_list = ['word1 1234 123 1', 'word2 123 43 564', 'somethingelse 123,4124,56']
>>> for i in my_list:
...     parts = re.split(r'[, ]', i)
...     my_dict[parts[0]] = parts[1:]
...
>>> my_dict
{'word2': ['123', '43', '564'], 'somethingelse': ['123', '4124', '56'], 'word1': ['1234', '123', '1']}

很明显,你不能两次拥有相同的key,否则值会被覆盖。

没有 re 模块的方法:

>>> for i in my_list:
...     parts = i.replace(',', ' ').split()
...     my_dict[parts[0]] = parts[1:]
...

【讨论】:

  • 你真的需要正则表达式吗? :P
  • @VasiliSyrakis:不,你也可以在拆分前用空格替换每个逗号。
  • 我们不确定它是否能回答问题
  • @Jean-FrançoisFabre:问题在我回答后已被编辑,不再相同。实际上完全不清楚。
【解决方案2】:

已编辑

输出字典

我会使用 re 和 findall 组合的字符串分区方法

import re

my_dict = {}
my_list = ['wordA 1234 123 1', 'wordB 123 43 564', 'somethingelse 123,4124,56']

for item in my_list:
    my_dict[item.partition(' ')[0]] = re.findall('\d+', item)

print my_dict

上面的代码会产生下面的字典

{'wordA': ['1234', '123', '1'], 'wordB': ['123', '43', '564'], 'somethingelse': ['123', '4124', '56']}

如果您希望多次使用相同的单词,您需要重写循环以检查键是否存在并将新值附加到现有列表中。

输出列表列表

如果不需要字典,我会使用 re 和列表理解

my_newlist = [re.findall('\d+', item) for item in my_list]

print my_newlist

上面的代码结果如下列表

[['1234', '123', '1'], ['123', '43', '564'], ['123', '4124', '56']]​

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-06
    • 2010-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-24
    相关资源
    最近更新 更多