简体   繁体   English

有没有办法在 Python 中创建一个由列表给出的长度为“n”的元组。?

[英]Is there a way to create a tuple in Python with a lenght 'n' given by a list.?

In my case I have a list of assets and I want to create a tuple (0,1.0) for defining a constraint for each asset.就我而言,我有一个资产列表,我想创建一个元组 (0,1.0) 来定义每个资产的约束。 If I have 3 assets i can just create the tuple by:如果我有 3 个资产,我可以通过以下方式创建元组:

bounds = ((0,1.0),(0,1.0),(0,1.0)) 

How can I automate this process if for example I have 1000 assets?例如,如果我有 1000 个资产,我该如何自动化这个过程?

Use a generator expression.使用生成器表达式。

bounds = tuple((0, 1.0) for _ in range(1000))

If you already have some other non-tuple iterable of constraints, just pass it to tuple :如果您已经有一些其他非元组可迭代约束,只需将其传递给tuple

bounds = tuple(the_constraints)

since tuples are immutable you can just use multiplication to create 1000 identical tuples由于元组是不可变的,因此您可以使用乘法来创建 1000 个相同的元组

bounds = ((0, 1.0),)*1000

(caution: do not do that with list type as it just duplicates the reference) (注意:不要用list类型这样做,因为它只是复制引用)

如果资产列表是列表列表,则只需将元组映射到它们:

tuple(map(tuple, asset_list))

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

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