【问题标题】:Storing the values in list Python将值存储在列表 Python 中
【发布时间】:2020-03-18 17:00:31
【问题描述】:

在下面的程序中,我使用 append() 函数将熵存储在列表中。 我在程序中有 36 个对话,我想将一个对话的熵存储到列表中,然后为第二个对话更新同一变量中的值,第三个对话熵也更新同一列表中的值。

但是 append() 函数将追加列表中所有对话的所有熵,但不会更新值。

我的程序如下:

import numpy as np
import csv
from scipy.stats import entropy
from math import log10
import statistics
import matplotlib.pyplot as plt


store_entropy = []
critical_entropy = 0
position = 0
outputfile = open("Output.txt","w")
with open('data.csv', 'r') as file:
    reader = csv.reader(file)
    for line in reader:
        lines = filter(None, line[2:])
        lines1 = ' '.join(lines).split(',')

        for row in lines1[::]:
            makeOneLine = row.rstrip('\n')
            delimiter = " "
            makeOneLine = delimiter.join(makeOneLine.split(delimiter, 3))
            numpyArraysDisplay = np.array(list(makeOneLine.split(" ")))
            print(numpyArraysDisplay)
            outputfile.write(str(numpyArraysDisplay) + '\n')

        #Loop for first segment
            for x in range(0, numpyArraysDisplay.size):
                part1 = numpyArraysDisplay[:x + 1]  # First segment divide
                strings, counts = np.unique(part1, return_counts=True)
                CountWordsfrequency = np.array(list(dict(zip(strings, counts)).values()))
                print(CountWordsfrequency)
                outputfile.write(str(CountWordsfrequency) + '\n')

                for y in range(0, CountWordsfrequency.size):
                    probability = CountWordsfrequency[y]/ part1.size
                    outputfile.write("Probability is \t" + str(probability) + '\n')
            ent2 = entropy(counts,base=10)
            outputfile.write("Entropy is \t" + str(ent2) + '\n')
            store_entropy.append(ent2)

如果我打印store_entropy 列表,那么它将打印列表中从第一个对话到最后一个对话的所有值。我希望第一个对话熵存储在变量中,当循环第二次运行时,第二个对话熵更新第一个不附加它。

我的输出是:

[0.0, 0.30102999566398114, 0.4771212547196623, 0.4515449934959717,0.0,0.6179053239112496, 
 0.6135103844338377, 0.6097931356022916]

预期是:

[0.0, 0.30102999566398114, 0.4771212547196623, 0.4515449934959717]
[0.0, 0.6179053239112496,0.6135103844338377, 0.6097931356022916]

请告诉我是否有人有解决方案。

【问题讨论】:

  • 能否知道data.csv 的行数和列数
  • @Solen'ya :行 = 36,列不固定。
  • 你做过调试吗?您的代码难以阅读,因为您对变量使用了至少 3 种不同的命名约定。另外,请提供minimal reproducible example。据我所知,这里没有理由使用 NumPy 数组,这样只会进一步混淆代码。

标签: python list


【解决方案1】:

我得到了上述问题的解决方案,并且通过下面的代码实现了预期的输出。

size = len(store_entropy)
idx_list = [idx for idx, val in enumerate(store_entropy) if val == 0.0]
res = [store_entropy[i: j] for i, j in zip([0] + idx_list, idx_list + ([size] if 
idx_list[-1] != size else []))]
# print(res)
res2 = [x for x in res if x != []]
print(res2)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-02
    • 1970-01-01
    • 2019-10-28
    • 1970-01-01
    • 1970-01-01
    • 2020-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多