0

This question, though specific in nature, can be abstracted to a general question about Python.

Imagine there is a function that takes in a few parameters. This list of parameters is of variable length; however, the types of the given parameters are not variable. The parameters come in groups of three, and the first and second are lists of floats and the third is a string. Then it repeats. So, in a way, the parameters are not of variable length, it's restricted to multiples of 3.

The types can be anything, those are just the ones specific to my problem. I have a matplotlib plot function that looks like this in the docs:

a.plot(x1, y1, 'g^', x2, y2, 'g-',...)

As you can see, number of groups of three can be however long you want.

I have a list of lists that contains all of my x values (x1, x2, x3, ...) and a list of lists that contain all of my y values (y1, y2, y3,...). Not knowing how long those lists are (they are always equal in length to each other, though), and assuming I can have some dictionary that maps certain indexes to certain strings (for the string parameter), how can I pass indexes from variables length list of lists to this function.

Ideally, I guess it would look something like this is pseudo-code:

for element in list_of_lists:
    myFunction(lists_of_lists[element])

Except that this code would just execute the myFunction for all the elements in the list_of_lists. Instead, I want one long list of parameters and only execute the function once. I also feel like this problem is interested for Python as a whole, not just my specific issue. Thanks in advance!

4

1 回答 1

1

给定 n 个等长的列表(例如):

a = [x1, x2, x3]
b = [y1, y2, y3]
c = ['g^', 'g-', 'g+']

zip将从每个列表中取出一个元素,并按照传入的顺序将它们放入一个元组中。

在我们的示例中,zip(a, b, c)返回:

[(x1, y1, 'g^'), (x2, y2, 'g-'), (x3, y3, 'g+')]

现在将其传递给绘图:

list_of_tuples = zip(a, b, c)
denormalized = [x for tup in list_of_tuples for x in tup]
plot(*denormalized)

[x for tup in list_of_tuples for x in tup]是一个列表推导,它将for x in tup为每个tupin执行list_of_tuples并将每个 x 附加到最终列表中。换句话说,它将元组列表扁平化为列表。

在我们的示例中,denormalized变为

[x1, y2, 'g^', x2, y2, 'g-', x3, y3, 'g+']

它在功能上等同于:

denormalized = []
for tup in list_of_tuples:
    for x in tup:
        denormalized.append(x)

当应用于列表时,解包运算符 (*) 告诉 python 调用该函数,列表中的每个元素都像作为位置参数传入一样。

于 2013-11-07T20:15:57.917 回答