简体   繁体   English

当内部列表的数量未知时,如何将列表列表送入* args?

[英]How to feed a list of lists into *args when the number of inside lists is unknown?

I've got a function which takes positional arguments in this format. 我有一个函数,该函数采用这种格式的位置参数。 Editing it isn't feasible for my use case (long story). 对于我的用例(长话来说),编辑它是不可行的。

import pandas as pd
import numpy as np
import random

def dummy_func(*args):

    outlist = []

    for arg in args:
        arg.append(42)

        outlist.append(arg)

    return outlist

Normally, function accepts any number of lists of integers in the following format and processes them like this: 通常,函数接受以下格式的任意数量的整数列表,并按以下方式处理它们:

s1 = [random.randrange(1, 101, 1) for _ in range(10)]
s2 = [random.randrange(1, 101, 1) for _ in range(10)]
s3 = [random.randrange(1, 101, 1) for _ in range(10)]

dummy_func(s1,s2,s3)

I'm trying to build a function that assembles a list of lists of integers to feed to the dummy_func listed above. 我正在尝试构建一个函数,该函数汇编一个整数列表以馈送到dummy_func列出的dummy_func The lists are all the same length, but we're feeding them to the function in batches and we don't know how many lists will be in each batch. 列表的长度都是相同的,但是我们将它们分批馈送到函数中,我们不知道每批中有多少个列表。

def analyse_some_series():

    # Generate a random number of lists
    count = np.random.choice(10)

    for i in range(count):

        mylist = [random.randrange(1, 101, 1) for _ in range(10)]

        outer_list.append(mylist)

    # This does not work for some reason
    finalfunc(outer_list)

For some reason, when you feed the list of lists to the function, it does not unwrap and process the list of lists. 由于某些原因,当您将列表列表提供给函数时,它不会解包和处理列表列表。 Instead it just sees one list object in the wrong format. 相反,它只会看到一个格式错误的列表对象。

Now normally I would just do something like: 现在通常我会做类似的事情:

x,y,z = series_list

But that won't work here since we don't know how many lists are going to be generated. 但这在这里行不通,因为我们不知道将要生成多少个列表。

Any help you could offer would be greatly appreciated. 您能提供的任何帮助将不胜感激。

Call it as finalfunc(*outer_list) . 将其称为finalfunc(*outer_list)

The asterisk does the unpacking for you. 星号为您解包。

Note that the asterisk in the function signature means that multiple items are packed into a single list, but in calling the function with a list it means that items of a list are unpacked into individual arguments. 请注意,函数签名中的星号表示将多个项目打包到一个列表中,但是在使用列表调用函数时,这意味着将列表中的项目解包到各个参数中。 Hence, the asterisk means opposite things in the two places, but it does the only sensible packing/unpacking related job in both situations so I think it's reasonable to use the same symbol. 因此,星号在两个地方表示相反的意思,但是在两种情况下它仅执行与包装相关的明智工作,因此我认为使用相同的符号是合理的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM