注意:python --version
生成 Python 3.6.4::Anaconda, Inc.
我正在使用一些 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])
输出:
type: <class 'tuple'> , item: ()
type: <class 'tuple'> , item: (1,)
type: <class 'tuple'> , item: (2,)
type: <class 'tuple'> , item: (3,)
type: <class 'tuple'> , item: (1, 2)
type: <class 'tuple'> , item: (1, 3)
type: <class 'tuple'> , item: (2, 3)
type: <class 'tuple'> , item: (1, 2, 3)
嗯。我可以覆盖循环值:
# attempt 1: just cast to np.array(item)
for item in powerset(value_list):
item = np.array(item)
# carry on
但这似乎有点太C了。这就是我想做的:
# 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”?
我的谷歌搜索没有在 stackoverflow 上出现任何关于此问题的问题,但如果我是第一个真正提出问题的人,我会感到惊讶。也许我没有使用正确的关键字进行搜索。
我已阅读 this w3schools entry on 'as' ,但它没有说明有关在 for 循环中使用的任何内容。如果 w3schools 上没有,我猜这不是 Python 能做到的事情,但我还是想检查一下 stackoverflow。
最佳答案
否
self 回答:除了通过评论之外,没有人提供“答案”,因此重新发布评论的实质内容以将OP标记为“已回答”。
关于Python - 有没有办法将 "as"别名添加到 for 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53548697/