python - 使用 Python 将 dict 解析为特定的列表格式
问题描述
说我有以下字典
{'red':'boop','white':'beep','rose':'blip'}
我想把它放到这样的列表中
['red','boop','end','white','beep','rose','blip','end']
要放置在列表前面的键/值是输入。
所以我本质上我想要[first_key, first_value,end, .. rest of the k/v pairs..,end]
我写了一个蛮力方法,但我觉得有一种更 Pythonic 的方式来做它(也因为一旦实现该片段将使我的代码 O(n^2) )
for item in lst_items
data_lst = []
for key, value in item.iteritems():
data_lst.append(key)
ata_lst.append(value)
#insert 'end' at the appropiate indeces
#more code ...
任何pythonic方法?
解决方案
下面依赖于itertools.chain.from_iterable
将项目展平为单个列表。我们从 中提取前两个值chain
,然后使用它们来构建一个新列表,我们用其余的值扩展该列表。
from itertools import chain
def ends(d):
if not d:
return []
c = chain.from_iterable(d.iteritems())
l = [next(c), next(c), "end"]
l.extend(c)
l.append("end")
return l
ends({'red':'boop','white':'beep','rose':'blip'})
# ['rose', 'blip', 'end', 'white', 'beep', 'red', 'boop', 'end']
如果您首先知道您想要的键,并且不关心其余的,我们可以使用惰性求值的生成器表达式将其从展平列表中删除。
def ends(d, first):
if not d:
return []
c = chain.from_iterable((k, v) for k, v in d.iteritems() if k != first)
l = [first, d[first], "end"]
l.extend(c)
l.append("end")
return l
ends({'red':'boop','white':'beep','rose':'blip'}, 'red')
# ['red', 'boop', 'end', 'rose', 'blip', 'white', 'beep', 'end']
推荐阅读
- java - 如何保持 Spring 上下文打开?
- asp.net-core - 如何将 IHttpContextAccessor 添加到 AuthorizationHandler
- javascript - 在 Javascript 或 Ruby 中将纪元时间转换为十进制年份
- python - python - 在pygame中碰撞后如何在其他地方随机生成敌人?
- javascript - 评估javascript在flutter webview中花费的时间太长?
- python - 使用分箱 X 值 Python 制作条形图
- javascript - 如何将对象数组转换为单个对象
- python - 从列表中删除较早的重复项并保持顺序
- linq - 如何在三列上编写 LINQ 查询,每列具有不同的值
- java - (JAVA)如何将双精度从列表转换为整数