【发布时间】:2016-11-01 15:02:51
【问题描述】:
我正在尝试从拆分字符串创建有序字典。如何维护拆分字符串的顺序?抱歉,我最初的示例令人困惑,并且与有序字典的想法相矛盾。这是一个不同的问题,但我不确定如何拆分字符串。
我的示例文件“practice_split.txt”如下:
§1 text for chapter 1 §2 text for chapter 2 §3 text for chapter 3
我希望我的有序字典看起来像:
OrderedDict([('§1', 'text for chapter 1'), ('§2', 'text for chapter 2'), ('§3', 'text for chapter 3')])
代替:
OrderedDict([('1 text for chapter 1 ', '\xc2\xa7'), ('\xc2\xa7', '3 text for chapter 3'), ('2 text for chapter 2 ', '\xc2\xa7')])
这是我的代码:
# -*- coding: utf-8 -*
import codecs
import collections
import re
with codecs.open('practice_split.txt', mode='r', encoding='utf-8') as document:
o_dict = collections.OrderedDict()
for line in document:
conv = line.encode('utf-8')
a = re.split('(§)', conv)
a = a[1:len(a)]
for i in range(1, len(a) - 1):
o_dict[a[i]] = a[i+1]
print o_dict
谢谢!
【问题讨论】:
-
为什么最后一个 dict 项与其他项不同?
-
这完全不清楚,是一个 XY 问题。你真正想做什么?您的预期输出是不可能的,因为您一遍又一遍地映射相同的键并期望 dict 保存所有值。这不是 dicts 的工作方式。
-
你永远无法得到你想要的结果
OrderedDict([('\xc2\xa7', 'text for chapter 1'), ('\xc2\xa7', 'text for chapter 2'), ('\xc2\xa7', 'text for chapter 3')]),因为所有字典条目的键都是相同的,这是不可能的。 -
@MosesKoledoye 抱歉解决了这个问题,谢谢!
-
除此之外,您的意思是一次遍历列表中的两个条目,而不是像多个答案中指出的那样一次遍历一个条目。
标签: python list ordereddictionary