我正在使用 itertools.product 功能。我有一个 2-deep 嵌套列表,它是一个可迭代列表。我想将此传递给产品功能不知道如何正确格式化它。
说清楚,我想要
In [37]: [k for k in product([1,2],['a','b'])]
Out[37]: [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]
Run Code Online (Sandbox Code Playgroud)
但从这样的嵌套列表输入生成
nested_list = [[1,2],['a','b']]
Run Code Online (Sandbox Code Playgroud)
但我得到了
In [36]: [k for k in product(nested_list)]
Out[36]: [([1, 2],), (['a', 'b'],)]
Run Code Online (Sandbox Code Playgroud) 我正在尝试生成数字列表的所有n项组合,同时保持数字顺序.例如,如果列表是
[1,2,3,4]
Run Code Online (Sandbox Code Playgroud)
长度为3的有序组合将是:
[1,2,3]
[2,3,4]
[1,2,4]
[1,3,4]
Run Code Online (Sandbox Code Playgroud)
需要说明的是,我必须保持数字顺序,因此[1,4,2]不会是理想的结果.
是否有一个功能可以做到这一点,还是一个快速算法可以完成它?实际列表是111,我将选择100项.谢谢.
我需要遍历一个列表并在到达最后一个项目时返回到第一个元素。
在cycle从对象itertools是专为这一点。
myList = [1,2,3,4,5,6,7,8,9]
i = 0
for item in cycle(myList):
index = i%9
print (index)
i += 1
Run Code Online (Sandbox Code Playgroud)
除了使用i变量还有其他方法吗?
我有一个itertools.combinations(big_matrix,50)带有 的迭代器big_matrix.shape = (65,x),所以大约有 10^14 种组合。我想获得 10000 个这样的组合的随机子集,也作为迭代器,以节省内存。
我尝试了 itertools 食谱
def random_combination(iterable, r):
"Random selection from itertools.combinations(iterable, r)"
pool = tuple(iterable)
n = len(pool)
indices = sorted(random.sample(xrange(n), r))
return tuple(pool[i] for i in indices)
Run Code Online (Sandbox Code Playgroud)
但tuple(iterable)会创建一个包含 10^14 个值的元组,并且该函数不返回迭代器而是返回数组。
random.sample不起作用,因为它无法获取itertools.combinations对象中的元素数量。
有什么办法可以做到这一点吗?
让我们假设我有一个整数列表:
mylist = [101, 102, 103, 104, 105, 106]
Run Code Online (Sandbox Code Playgroud)
现在我需要创建每个可能的子列表分区(保留顺序):
sublists = [([101], [102, 103, 104, 105, 106]),
([101, 102], [103, 104, 105, 106]),
([101, 102, 103], [104, 105, 106]),
...
([101, 102], [103, 104], [105, 106]),
...
([101], [102, 103, 104], [105], [106]),
...
([101], [102], [103], [104], [105], [106])]
Run Code Online (Sandbox Code Playgroud)
任何的想法?将itertools是有益的?
我有一个脚本,它获取目录中的所有 csv 文件并使用外部联接将它们并排合并。问题是当我尝试在我需要加入的文件上使用它时,我的计算机窒息(MemoryError)(大约两打文件,每个 6-12 Gb)。我知道 itertools 可用于提高循环效率,但我不清楚它是否或如何应用于这种情况。我能想到的另一种选择是安装 mySQL,学习基础知识,然后在那里执行此操作。显然,如果可能的话,我宁愿在 Python 中执行此操作,因为我已经在学习它。基于 R 的解决方案也是可以接受的。
这是我的代码:
import os
import glob
import pandas as pd
os.chdir("\\path\\containing\\files")
files = glob.glob("*.csv")
sdf = pd.read_csv(files[0], sep=',')
for filename in files[1:]:
df = pd.read_csv(filename, sep=',')
sdf = pd.merge(sdf, df, how='outer', on=['Factor1', 'Factor2'])
Run Code Online (Sandbox Code Playgroud)
关于如何处理对于我的计算机内存来说太大的文件的任何建议将不胜感激。
我正在尝试实现我自己的版本itertools.compress,问题是我偶然发现了返回类型。我的意思是这两个函数都返回一个迭代器,但我认为第二个函数不被视为生成器函数,因为里面没有 yield 语句。所以我的问题是,这两个实现是等价的吗?
def compress (seq, selectors):
from operator import itemgetter
fst = itemgetter (0)
snd = itemgetter (1)
yield from map (fst, filter (snd, zip (seq, selectors)))
def compress (seq, selectors):
from operator import itemgetter
fst = itemgetter (0)
snd = itemgetter (1)
return map (fst, filter (snd, zip (seq, selectors)))
Run Code Online (Sandbox Code Playgroud) 我有一个非常奇怪的问题,似乎找不到解决方法.
下面的代码找到素数因子分解n,将素因子放入列表然后找到素因子的所有可能的和变量,并打印出该列表的唯一值.
示例:44的素数因子是2*2*11,因此44将打印出来
2,2+2,11,2+11,2+2+11 = 2,4,11,13,15:
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
import math
import sys
import itertools
from itertools import permutations
def primes(n):
primfac = []
d = 2
while d*d <= n:
while (n % d) == 0:
primfac.append(d)
n //= d
d += 1
if n > 1:
primfac.append(n)
return primfac
def primecombo(n):
b = []
for i in range(1, len(primes(n))+1):
for subset in permutations(primes(n), i):
b.append(sum((subset)))
a = list(set(b))
a.sort()
return a
Run Code Online (Sandbox Code Playgroud)
代码本身似乎在大多数情况下工作得很好而且效率很高但是由于一些非常奇怪的原因,当你处理任何只有素数因素为2的数字时,它变得非常慢.
如果你尝试打印primecombo(444444)或打印primecombo(23452823)它几乎会立即打印结果,但如果你尝试2048或4096它真的很慢.
任何人都可以看到为什么会这样,我可以做些什么来解决它?
我正在关注本教程https://towardsdatascience.com/evaluate-topic-model-in-python-latent-dirichlet-allocation-lda-7d57484bb5d0并找到问题。所以我对这段代码的目的是在主题、alpha 和 beta 参数值的范围内对其进行迭代。所以我可以从 alpha 和 beta 生成的一致性分数中确定最佳主题数
def compute_coherence_values(corpus, dictionary, k, a, b):
lda_model = gensim.models.LdaMulticore(corpus=corpus,
id2word=id2word,
num_topics=10,
random_state=100,
chunksize=100,
passes=10,
alpha=a,
eta=b,
per_word_topics=True)
coherence_model_lda = CoherenceModel(model=lda_model, texts=data_lemmatized, dictionary=id2word, coherence='c_v')
return coherence_model_lda.get_coherence()
Run Code Online (Sandbox Code Playgroud)
进而
import numpy as np
import tqdm
grid = {}
grid['Validation_Set'] = {}
# Topics range
min_topics = 2
max_topics = 11
step_size = 1
topics_range = range(min_topics, max_topics, step_size)
# Alpha parameter
alpha = list(np.arange(0.01, 1, 0.3))
alpha.append('symmetric')
alpha.append('asymmetric')
# Beta parameter
beta = …Run Code Online (Sandbox Code Playgroud) python python-itertools python-3.x long-integer topic-modeling
身份列表包含大约57000 张图像的大数组。现在,我正在借助itertools.product(). 这将整个列表存储在内存中,这非常昂贵,并且我的系统在 4 分钟后挂起。
如何优化以下代码并避免节省内存?`
for i in range(0, len(idendities) - 1):
for j in range(i + 1, len(idendities)):
cross_product = itertools.product(samples_list[i], samples_list[j])
cross_product = list(cross_product)
for cross_sample in cross_product:
negative = []
negative.append(cross_sample[0])
negative.append(cross_sample[1])
negatives.append(negative)
print(len(negatives))
negatives = pd.DataFrame(negatives, columns=["file_x", "file_y"])
negatives["decision"] = "No"
negatives = negatives.sample(positives.shape[0])
Run Code Online (Sandbox Code Playgroud)
内存9.30会越来越高,有一点系统已经完全挂了。
我还根据他的回答实现了以下答案并修改了代码。
for i in range(0, len(idendities) - 1):
for j in range(i + 1, len(idendities)):
for cross_sample in itertools.product(samples_list[i], samples_list[j]):
negative = [cross_sample[0], cross_sample[1]]
negatives.append(negative)
print(len(negatives)) …Run Code Online (Sandbox Code Playgroud) python ×10
python-itertools ×10
combinations ×2
list ×2
python-3.x ×2
cycle ×1
indexing ×1
iterator ×1
large-files ×1
long-integer ×1
merge ×1
optimization ×1
pandas ×1
performance ×1
permutation ×1
product ×1
random ×1
yield-from ×1