【发布时间】: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