python:解压列表和集合 [英] python: unpacking the lists and sets

查看:36
本文介绍了python:解压列表和集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个必须解包列表的代码,我的意思是转

I've written a code that had to unpack lists, I mean turn

[无, [1, ({2, 3}, {'foo': 'bar'})]]

[None, [1, ({2, 3}, {'foo': 'bar'})]]

进入

[无, 1, 2, 3, 'foo', 'bar']

[None, 1, 2, 3, 'foo', 'bar']

实际上,这是我的解决方案:

Actually, this is my solution:

    import re
def unpack(l):
    pattern = r"\w+"
    fin = []
    for i in l:
        match = re.findall(pattern, i)
        fin.append(match)
    return fin

但它会导致问题 TypeError: expected string or buffer 是的,我已经查看了其他类似的问题.请告诉我如何正确操作

but it causes problem TypeError: expected string or buffer and, yes, I've looked through other similar questions. Please tell me how to do it correctly

和正则表达式准确地选择我需要的

and regex chooses accurately what I need

推荐答案

您不能将正则表达式应用于列表.您可以使用str将列表转换为字符串,然后然后应用正则表达式,但您可能不应该这样做.*)

You can not apply a regular expression to a list. You could turn the list into a string using str, and then apply the regex, but you probably should not.*)

相反,我建议使用递归函数来展平列表,并迭代任何嵌套字典中的键和值,并将其递归应用于任何嵌套列表、集合、元组或字典.

Intead, I suggest a recursive function for flattening the list, and also iterating both the keys and values in any nested dictionaries, and applying itself recursively to any nested lists, sets, tuples or dicts.

def unpack(seq):
    if isinstance(seq, (list, tuple, set)):
        yield from (x for y in seq for x in unpack(y))
    elif isinstance(seq, dict):
        yield from (x for item in seq.items() for y in item for x in unpack(y))
    else:
        yield seq

lst = [None, [1, ({2, 3}, {'foo': 'bar'})]]
print(list(unpack(lst)))
# [None, 1, 2, 3, 'foo', 'bar']

更新:对于 Python 2.x,将 yield from (...) 替换为 for x in (...): yield x,或直接 return 列表而不是使用生成器来yield 元素:

Update: For Python 2.x, replace the yield from (...) with for x in (...): yield x, or directly return lists instead of using a generator to yield elements:

def unpack(seq):
    if isinstance(seq, (list, tuple, set)):
        return [x for y in seq for x in unpack(y)]
    elif isinstance(seq, dict):
        return [x for item in seq.items() for y in item for x in unpack(y)]
    else:
        return [seq]

<小时>

*) 既然你问:如果数字包含一个点,或者字符串包含……嗯,什么?此外,您必须从匹配的字符串中重新创建具有正确类型(如 int)的实际对象.如果列表包含除字符串或数字以外的对象,并且不能轻易地从它们的字符串表示中重新创建,该怎么办?


*) Since you asked: what if the numbers contain a dot, or the strings contain... well, anything? Also, you'd have to recreate the actual objects with their proper type (like int) from the matched strings. And what if the list contains objects other than strings or numbers, that can not easily be recreated from their string representation?

这篇关于python:解压列表和集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆