【问题标题】:the output is not in correct order输出顺序不正确
【发布时间】:2019-01-17 15:24:24
【问题描述】:

我在 python2.7 中有一个代码,它获取一行文本作为其列表元素并将其作为 json 返回。这是代码:

import itertools

lines=["Hamlet"
   ,"William Shakespeare",
   "Edited Barbara B Mowat Paul Werstine"
   ,"Michael Poston Rebecca Niles"]
LinesMap=dict()
for line in lines:
    list=[l for l in line.split(' ')]
    d = dict(itertools.izip_longest(*[iter(list)] * 2, fillvalue=None))
    LinesMap.update(d)

print(LinesMap)

输出是:

{'William': 'Shakespeare', 'Edited': 'Barbara', 'B': 'Mowat',    

'Michael':'Poston', 'Paul': 'Werstine', 'Rebecca': 'Niles', 'Hamlet': None}

应该是这样的:

{'Hamlet': None, 'William': 'Shakespeare', 'Edited': 'Barbara', 

'B':'Mowat', 'Paul': 'Werstine', 'Michael': 'Poston', 'Rebecca': 'Niles'}

如果我把列表加长,那就更糟了!为什么这不是正确的顺序?但是当我在 python3.6 中运行相同的代码时,当然使用 python3 语法,顺序是正确的。 python3.6代码为:

import itertools

lines=["Hamlet"
   ,"William Shakespeare",
   "Edited Barbara B Mowat Paul Werstine"
   ,"Michael Poston Rebecca Niles"]
LinesMap=dict()
for line in lines:
   list=[l for l in line.split(' ')]
   d = dict(itertools.zip_longest(*[iter(list)] * 2, fillvalue=None))
   LinesMap = {**LinesMap, **d}

print(LinesMap) 

这是一个问题。另一个是短名单可以正常运行。但是当列表较长且元素过多时,输出不会显示任何内容,并且似乎已损坏。这是在 Windows 中,在 linux 中它不会中断。有什么问题?

ps:由于某些原因,我必须在 python 2.7 中运行它!

【问题讨论】:

  • 字典在 Python 3.6 之前没有排序 - 这意味着您不能依赖早期版本中的任何特定顺序。
  • 如果你被限制在 2.7,你可能想试试from collections import OrderedDict
  • 还在“Hamlet”中添加一个空格,以便添加“None”条目。
  • 看起来您希望它们按输入顺序排列。尝试from Collections import OrderedDict 并使用它而不是dict

标签: python python-3.x python-2.7 dictionary


【解决方案1】:

Python dict 对象没有内在的顺序,除非是在最近的 Python 版本中,所以你不能假设你会按照放入对象的顺序取出对象。

如果您需要该功能,可以使用 OrderedDict 对象。

import random
from collections import OrderedDict

# Normal dict behavior:
numbers = {}
random_nums = (random.random() for _ in range(1000))
for i in random_nums:
    numbers[i] = random.random()
assert list(numbers.keys()) != list(random_nums)

# Ordered dict behavior:
numbers = OrderedDict()
for i in random_nums:
    numbers[i] = random.random()
assert list(numbers.keys()) == list(random_nums)

【讨论】:

  • 是的,尽管您的 assert 并不能证明任何事情,但常规的 dict 在 Python 2 中也传递了这个断言(编辑:因为整数大多是自己散列 - 在下面回答您的问题)
  • 我们去,用随机数代替
  • 证明一个数据结构是保证命令只是不可能从几个例子,相反你应该只链接到文档或语言规范
  • 我使用了 OrderedDict 而不是 dict,输出为: OrderedDict([('Hamlet', None), ('William', 'Shakespeare'), ('Edited', 'Barbara'), ('B', 'Mowat'), ('Paul', 'Werstine'), ('Michael', 'Poston'), ('Rebecca', 'Niles')]) 所以顺序是正确的。但我怎样才能获得这种格式的所需输出:{'Hamlet': None, 'William': 'Shakespeare', 'Edited': 'Barbara', 'B':'Mowat', 'Paul': '韦斯汀,“迈克尔”:“波斯顿”,“丽贝卡”:“奈尔斯”}
  • 为什么要这样格式化?该格式表明表示的对象是普通的旧字典,而 OrderedDict 不是。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-26
相关资源
最近更新 更多