python - 转换为 dict/type 列表,包含字符串列表的字符串列表?
问题描述
a = ['foo', 'bar', ['can', 'haz']]
希望对每对字符串应用一个函数,替换它们,包括列表中的那些。例如,
f = lambda k,v: {'key': k, 'val': v}
所以f(a)
会变成:
[{'key': 'foo', 'val': 'bar'}, [{'key': 'can', 'val': 'haz'}]]
上面a
只有 2 个维度,但我会对k个维度感兴趣。在明确用 a或 otherboltons.iterutils.remap
替换每个层次结构级别的所有非列表元素不是正确的用例
之前就开始对某些东西进行黑客攻击......</p>dict
f
编辑:另一个例子
# create some random variables, alternative: `locals().update({c: (round(…`
a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z = tuple(
(round(abs(random()) ** 10, 4)
if randint(0, 1) % 2 == 0
else randint(20, 50)
if randint(0, 1) % 2 == 0
else ('foo', 'bar', 'can', 'haz', 'bzr')[randint(0, 4)])
for c in ascii_lowercase)
l1 = [a, b, c, d, e, f, g, [h, i, j, k],
l, m, n, [o, p, q, r, [s, t, u, v, w, x, y, z], a, b], c, d, e]
g = lambda k,v: {'{}_key'.format(k): k, '{}_val'.format(k): v}
当有一对彼此相邻时,它应该将类型构造函数 T 应用于它,并加入(我有一个add_to
支持字典、列表等的函数)任何先前直接相邻的 - 没有列表 inbetwixt - 否则原始标量应该以与之前相同的层次结构连接到列表中。这是 的预期输出g(l1)
,不包括对变量的评估:
[
{'a_key': a, 'a_val': b,
'c_key': c, 'c_val': d,
'e_key': e, 'e_val': f},
g,
[
{'h_key': h, 'h_val': i,
'j_key': j, 'j_val': k}
],
{'l_key': l, 'l_val': m},
n,
[
{'o_key': o, 'o_val': p,
'q_key': q, 'q_val': r},
[
{'s_key': s, 's_val': t,
'u_key': u, 'u_val': v,
'w_key': w, 'w_val': x,
'y_key': y, 'y_val': z}
],
{'a_key': a, 'a_val': b}
],
{'c_key': c, 'c_val': d},
e
]
解决方案
下面有一堆乱七八糟的东西,但里面的核心算法solution()
似乎还不错。我不能说我喜欢sentinel
那里,但是...它使其他一切都变得整洁。
https://repl.it/@altendky/ChartreuseWeightyRoot-10
import functools
import itertools
import random
import string
import attr
import toolz
@attr.s(frozen=True)
class Example:
source = attr.ib()
target = attr.ib()
group_handler = attr.ib()
def random_example():
a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z = tuple(
(round(abs(random.random()) ** 10, 4)
if random.randint(0, 1) % 2 == 0
else random.randint(20, 50)
if random.randint(0, 1) % 2 == 0
else ('foo', 'bar', 'can', 'haz', 'bzr')[random.randint(0, 4)])
for c in string.ascii_lowercase)
l1 = [a, b, c, d, e, f, g, [h, i, j, k],
l, m, n, [o, p, q, r, [s, t, u, v, w, x, y, z], a, b], c, d, e]
auauughhghhhh = [
{f'{a}_key': a, f'{a}_val': b,
f'{c}_key': c, f'{c}_val': d,
f'{e}_key': e, f'{e}_val': f},
g,
[
{f'{h}_key': h, f'{h}_val': i,
f'{j}_key': j, f'{j}_val': k}
],
{f'{l}_key': l, f'{l}_val': m},
n,
[
{f'{o}_key': o, f'{o}_val': p,
f'{q}_key': q, f'{q}_val': r},
[
{f'{s}_key': s, f'{s}_val': t,
f'{u}_key': u, f'{u}_val': v,
f'{w}_key': w, f'{w}_val': x,
f'{y}_key': y, f'{y}_val': z}
],
{f'{a}_key': a, f'{a}_val': b}
],
{f'{c}_key': c, f'{c}_val': d},
e
]
g = lambda k,v: {'{}_key'.format(k): k, '{}_val'.format(k): v}
return Example(
source=l1,
target=auauughhghhhh,
group_handler=functools.partial(process_group, paired_sequence_handler=lambda s: build_dict_by_update(s, g)),
)
def process_group(group, paired_sequence_handler):
processed_group = []
if len(group) == 0:
return processed_group
odd = (len(group) % 2) != 0
raw_pairs = group[:-1] if odd else group
pairs = toolz.partition_all(2, raw_pairs)
result = paired_sequence_handler(pairs)
processed_group.append(result)
if odd:
processed_group.append(group[-1])
return processed_group
def build_dict_by_update(sequence, pair_handler):
result = {}
for pair in sequence:
result.update(pair_handler(*pair))
return result
examples = [
Example(
source=['foo', 'bar', ['can', 'haz']],
target=[{'key': 'foo', 'val': 'bar'}, [{'key': 'can', 'val': 'haz'}]],
group_handler=functools.partial(process_group, paired_sequence_handler=lambda s: build_dict_by_update(s, lambda k,v: {'key': k, 'val': v})),
),
random_example(),
]
def solution(source, group_handler):
built = []
group = []
sentinel = object()
for value in itertools.chain(source, [sentinel]):
if not isinstance(value, list) and value is not sentinel:
group.append(value)
continue
built.extend(group_handler(group))
group = []
if value is sentinel:
break
result = solution(
source=value,
group_handler=group_handler,
)
built.append(result)
return built
for example in examples:
result = solution(
source=example.source,
group_handler=example.group_handler,
)
succeeded = result == example.target
print('?', succeeded)
if not succeeded:
print('? ', example.target)
print('? ', result)
推荐阅读
- android - 在 recyclerview kotlin 中显示来自 firebase 实时数据库的数据
- javascript - 在 chrome 中的 window.unload 事件上发送信标后清除 cookie
- php - if条件与foreach循环在php中的数组
- flutter - 我如何在 Flutter 中实现这种效果?
- python - 我的项目不断让我退出,为什么会这样?(关闭)
- java - Hibernate 类型映射短 vs 字节 / JPL 接口 vs 本机查询
- node.js - 如何在 Nodejs 中使用通配符扫描 AWS DynamoDB
- twig - Shopware 6 - 不使用自定义主题
- python - 比较两个不同数据框的“名称”列
- python - 如何在具有多个子文件夹的 Python 框架中导入模块