python 从包含元组、列表、集合和字典的列表中提取所有数值

guz6ccqo  于 2023-02-07  发布在  Python
关注(0)|答案(2)|浏览(136)

这是列表。我想从列表中提取所有数字,包括字典中键和值的数值。
列表1 =[1,2,3,4,[44,55,66,真],假,(34,56,78,89,34),{1,2,3,3,2,1},{1:34,"密钥2":[第55、67、78、89段]、第4段:(45,22,61,34)},[56,"数据科学"],"机器学习"]

def prod_list(lst):
    flat_list = []
# iterate over each element 
for i in lst: 

    # check if element is list or number 
    if type(i) == list or type(i) == tuple or type(i) == set or type(i) == dict: 
        # iterate over each nested list 
        for j in i: 
            # check if element is number 
            if type(j) == int or type(j) == float: 
                flat_list.append(j) 
            elif type(j) == dict:
                for k,v in j.items():
                    if type(v) == int or type(v) == float:
                        flat_list.append(v)

            elif type(j) == list or type(j) == tuple:
                for k in j:
                    if type(k) == int or type(k) == float:
                        flat_list.append(k)
    else: 
        # check if element is number 
        if type(i) == int or type(i) == float: 
            flat_list.append(i) 

# calculate product of list 
return(flat_list)

#I am expecting this list
n=[1,2,3,4,44,55,66,34,56,78,89,34,1,2,3,1,34,55,67,78,89,4,45,22,61,34,56]``your text``
j9per5c4

j9per5c41#

试试看:

def is_integer(x):
    return not isinstance(x, bool) and isinstance(x, int)

def get_numbers(o):
    if isinstance(o, dict):
        for k, v in o.items():
            if is_integer(k):
                yield k
            yield from get_numbers(v)
    elif isinstance(o, (list, tuple, set)):
        for v in o:
            if is_integer(v):
                yield v
            else:
                yield from get_numbers(v)
    else:
        if is_integer(o):
            yield o

list1 = [
    1,
    2,
    3,
    4,
    [44, 55, 66, True],
    False,
    (34, 56, 78, 89, 34),
    {1, 2, 3, 3, 2, 1},
    {1: 34, "key2": [55, 67, 78, 89], 4: (45, 22, 61, 34)},
    [56, "data science"],
    "Machine Learning",
]

print(list(get_numbers(list1)))

图纸:

[1, 2, 3, 4, 44, 55, 66, 34, 56, 78, 89, 34, 1, 2, 3, 1, 34, 55, 67, 78, 89, 4, 45, 22, 61, 34, 56]
uinbv5nw

uinbv5nw2#

从functools导入减少def产品(第一个):flatList =[],对于列表中的i:如果类型(i)==列表或类型(i)==元组或类型(i)==集合:对于i中的j:如果类型(j)==整数:平面列表.追加(j)elif类型(i)==字典:对于i. keys()中的a:如果类型(a)==整数:在i. values()中为b追加(a):如果类型(b)==整数:如果类型(b)==列表或类型(b)==元组,则追加(b):对于b中的c:如果类型(c)==整数:附加(c)否则:如果类型(i)==整数:append(i)返回平面列表列表1 =[1,2,3,4,[44,55,66,真],假,(34,56,78,89,34),{1,2,3,3,2,1},{1:34,"关键字2":[第55、67、78、89段]、第4段:(45,22,61,34)},[56,"数据科学"],"机器学习"]打印(产品(列表1))
我用了这个密码。

相关问题