我有以下输入:
input = [(dog, dog, cat, mouse), (cat, ruby, python, mouse)]
Run Code Online (Sandbox Code Playgroud)
并尝试输出以下内容:
outputlist = [[0, 0, 1, 2], [1, 3, 4, 2]]
outputmapping = {0:dog, 1:cat, 2:mouse, 3:ruby, 4:python, 5:mouse}
Run Code Online (Sandbox Code Playgroud)
关于如何处理可读性的任何提示(var输入可能变得非常大).
我正在使用 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) 作为我的问题的答案找到两个列表相同的基于1的位置我得到了使用C库itertools来加快速度的提示.
要验证我使用cProfile编写了以下测试:
from itertools import takewhile, izip
def match_iter(self, other):
return sum(1 for x in takewhile(lambda x: x[0] == x[1],
izip(self, other)))
def match_loop(self, other):
element = -1
for element in range(min(len(self), len(other))):
if self[element] != other[element]:
element -= 1
break
return element +1
def test():
a = [0, 1, 2, 3, 4]
b = [0, 1, 2, 3, 4, 0]
print("match_loop a=%s, b=%s, result=%s" % (a, b, match_loop(a, b)))
print("match_iter a=%s, b=%s, result=%s" % (a, b, match_iter(a, …Run Code Online (Sandbox Code Playgroud) 我试图找到字符串"0000111"的不同排列.所有不同的字符串包含三个1和4个0.这是我的代码:
p = itertools.permutations("0000111")
l = list(p)
print len(l) #5040
print len(set(l)) #35
Run Code Online (Sandbox Code Playgroud)
怎么了?还有更好的方法吗?
我需要遍历一个列表并在到达最后一个项目时返回到第一个元素。
在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变量还有其他方法吗?
让我们假设我有一个整数列表:
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)
关于如何处理对于我的计算机内存来说太大的文件的任何建议将不胜感激。
我正在关注本教程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
list ×3
combinations ×1
cprofile ×1
cycle ×1
dictionary ×1
indexing ×1
large-files ×1
long-integer ×1
mapping ×1
merge ×1
optimization ×1
pandas ×1
performance ×1
permutation ×1
product ×1
python-3.x ×1