Python有没有办法将“as”别名添加到for循环中?

2024-09-27 22:38:02 发布

您现在位置:Python中文网/ 问答频道 /正文

注意:python --version产生{}

我正在处理一些itertools代码,它们似乎很想输出元组,但我希望将每个结果作为numpy.array循环。使用案例:有一个包含10个特性的数据集,我很好奇为什么要强行将所有特性集组合起来以适应集群。在

所以我试了一下:

from itertools import chain, combinations
import numpy as np
def the_python_way(value_list):
    # creates a generator on an iterator; not sure which
    def powerset(iterable):
        # Note: Seems to forcefully make the results tuples. Casting the tuple 
        # produced by combinations(...) to something else seems to alter the 
        # production order a bit, but when I check the type produced by the 
        # final chain.from_iterable(...) it still says "tuple". Weird.
        return chain.from_iterable(
                np.array(combinations(iterable, len_n))
                for len_n in range(len(iterable)+1))

    for item in powerset(value_list):
        print("type: ", type(item), ", item: ", np.array(item))

the_python_way([1,2,3])

输出:

^{pr2}$

嗯。我可以重写循环值:

# attempt 1: just cast to np.array(item)
for item in powerset(value_list):
    item = np.array(item)
    # carry on

但这似乎有点过分了。我想做的是:

# attempt 2: syntax error
for np.array(value) as item in powerset(value_list):
    # carry on

不是更好,但我希望这能奏效。没有:

# attempt 5: syntax error
for np.array(value) in powerset(value_list) as item:
    # carry on

在for循环中有没有“as”的方法?

我的google搜索没有在stackoverflow上找到任何关于这个的问题,但是如果我是第一个真正问这个问题的人,我会感到惊讶。也许我没有用正确的关键字搜索。在

我读过this w3schools entry on 'as',但它没有提到在for循环中使用的任何内容。如果不是在w3schools上,我猜这不是Python能做的事情,但是我还是想检查stackoverflow。在


Tags: thetoinfromchainforvalueon

热门问题