转换成字典/类型列表,包含字符串列表的字符串列表?

时间:2020-03-01 04:31:01

标签: python functional-programming apply mutation list-manipulation

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 个维度感兴趣。开始与boltons.iterutils.remap一起入侵某些东西,然后才发现用dict或其他f替换每个层次结构级别上的所有非列表元素不是正确的用例……< / p>

编辑:另一个例子

# 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
]

3 个答案:

答案 0 :(得分:1)

下面有一堆乱七八糟的东西,但是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)

答案 1 :(得分:0)

您将需要递归以支持未定义数量的级别。

假设您的级别在每个级别的列表中始终有2或3个项目,则递归函数可能如下所示:

a = ['foo', 'bar', ['can', 'haz']]

def f(a):
    k,v,b,*_ = a+[None]
    result = [{"key":k,"val":v}]
    if b: result.append(f(b))
    return result

输出:

print(f(a))

# [{'key': 'foo', 'val': 'bar'}, [{'key': 'can', 'val': 'haz'}]]


b = ['foo', 'bar', ['can', 'haz', ['boo','yah',['dino','dog']]]]
print(f(b))
[
  {'key': 'foo', 'val': 'bar'},
  [
     {'key': 'can', 'val': 'haz'},
     [
        {'key': 'boo', 'val': 'yah'},
        [
          {'key': 'dino', 'val': 'dog'}
        ]
     ]
  ]
]

答案 2 :(得分:0)

假设每个列表的连续内容始终是键值对或一个列表:

a = ['foo', 'bar', ['can', 'haz']]

def f(a):
  itr = iter(a)
  return [f(a) if isinstance(x, list) else {'key': x, 'val': next(itr)} for x in itr]

# >>> f(a)
# [{'key': 'foo', 'val': 'bar'}, [{'key': 'can', 'val': 'haz'}]]

更新

好吧,我必须说这让我有些头疼,但是既然这是一个有趣的问题,而且是学习新知识的绝好机会,那么就在这里。
一个功能精确 1 您想要的是什么,因为递归操作存在一些问题:

有了您精确的功能和输入,我会得到RecursionError: maximum recursion depth exceeded while calling a Python object

不递归。我确定这不是最终解决方案,但可以正常工作:

from functools import reduce
import operator

def traverse(lst):
  stack = [lst]
  res = [[]]

  substack = stack[0]
  subres = res[0]

  depth = 0

  while stack:
    if substack:
      if isinstance(substack[0], list):
        substack = substack[0]
        subres.append([])
        subres = subres[-1]
        depth += 1
      else:
        if len(substack) > 1 and not isinstance(substack[1], list):
            subres.append({'key': substack.pop(0), 'val': substack.pop(0)})
        else:
          subres.append(substack.pop(0))
    else:
        substack = reduce(operator.getitem, [0] * depth, stack)
        subres = reduce(operator.getitem, [-1] * depth, res)
        depth -= 1
        substack.pop(0)

  return res[0]

Live Demo

1。如果您只是将list列表传递给函数,那么我不确定如何在输出示例中知道dict键的确切名字,所以我将由您自己决定。