简体   繁体   English

解包未指定数量的变量

[英]Unpacking an unspecified amount of variables

So I have a list of tuples. 所以我有一个元组列表。 Each tuple in the list will be the same length, but tuple size will vary based on list. 列表中的每个元组将具有相同的长度,但元组大小将根据列表而变化。 For example, one list could contain tuples of length 4, another could contain tuples of length 5. I want to unpack each individual value of a tuple, and use each value to multiply it by an element in another list. 例如,一个列表可以包含长度为4的元组,另一个列表可以包含长度为5的元组。我想解压缩元组的每个单独值,并使用每个值将其乘以另一个列表中的元素。 For example(with a list of tuples of length 3): 例如(带有长度为3的元组列表):

somelist = [a,b,c]
tuplelist = [(2,3,5),(5,7,5),(9,2,4)]
listMult = []
for x,y,z in tuplelist:
    listMult.append([somelist[0]*x,somelist[1]*y,somelist[2]*z])

The problem with this is that it won't scale if I'm using another list with tuples of a different size. 这个问题是,如果我使用另一个包含不同大小元组的列表,它将无法扩展。

If you don't know how many elements each tuple has, unpacking would be a bad idea. 如果您不知道每个元组有多少元素,那么解压缩将是一个坏主意。 In your example, you would instead do the following: 在您的示例中,您将改为执行以下操作:

listMult = [sum(x*y for x, y in zip(tup, somelist)) for tup in tuplelist]

In general, you'd try to use iteration, starargs, and other things that operate on an iterable directly instead of unpacking. 通常,您会尝试使用迭代,starargs和其他直接操作迭代的东西而不是解包。

As presented, the question is incompletely specified. 如上所述,问题未完全明确。 But there is an interesting and useful variant of the question, "How do I unpack a fixed number of elements from tuples of an unknown length?". 但是有一个有趣且有用的问题变体,“如何从未知长度的元组中解包固定数量的元素?”。

The answer to that might be useful to you: 答案可能对您有用:

tuple_list = [(2,3), (5,7,5), (9,2,4,2)]
pad_tuple = (0, 0, 0)
for t in tuple_list:
    t += pad_tuple             # make sure the tuple is sufficiently long
    x, y, z = t[:3]            # only extract the first three elements
    print(x,y,z)

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

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