【问题标题】:Creating python list with multiple elements and write to .csv创建具有多个元素的 python 列表并写入 .csv
【发布时间】:2017-01-17 04:50:09
【问题描述】:

我有这个在每次迭代中生成一个元素的小代码。 还会为每个元素生成一个标签。

count = 0
while (count<10):
    random.seed()
    tau = int(math.ceil(np.random.uniform(lorange, hirange)))
    count = count+1
    print('For', count,'th iter tau is', tau)

    X = [amplitude * np.exp(-t / tau)]
    print('And X is', X)

这给了我 -

For 1 th iter tau is 253
 And X is [-8.3319888120435905]
For 2 th iter tau is 733
 And X is [-8.5504619226105234]
For 3 th iter tau is 6
 And X is [-1.637157007733484]
For 4 th iter tau is 35
 And X is [-6.5137386619958191]
For 5 th iter tau is 695
 And X is [-8.544086302536952]
For 6 th iter tau is 987
 And X is [-8.5805340921808924]
For 7 th iter tau is 807
 And X is [-8.5611651675760001]
For 8 th iter tau is 820
 And X is [-8.5628471889130697]
For 9 th iter tau is 799
 And X is [-8.5601030426343065]
For 10 th iter tau is 736
 And X is [-8.5509374123154984]

现在我想得到一个列表,一个包含所有 X 值的列表。

我检查了堆栈问题here 并做了这个-

myList = []
myList.append([X for _ in range(no_tau)])
print(myList)

但是我没有将所有 X 元素作为一个列表获取,而是多次获取相同的元素(最后一个 X 值)。

[[[-8.5509374123154984], [-8.5509374123154984], [-8.5509374123154984], [-8.5509374123154984], [-8.5509374123154984], [-8.5509374123154984], [-8.5509374123154984], [-8.5509374123154984], [-8.5509374123154984], [-8.5509374123154984]]]

如何多次获取列表中的所有 X 元素而不是相同的元素?

我还想稍后以 .csv 格式编写此列表。任何帮助将不胜感激。谢谢

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    X 是一个包含单个元素的列表。然后当你这样做时:

    myList.append([X for _ in range(no_tau)])
    

    您正在添加具有唯一元素(最后一个)len(range(no_tau)) 次的列表。

    您需要在迭代时添加它。像这样的:

    count = 0
    myList = []
    while (count<10):
        tau = int(math.ceil(np.random.uniform(lorange, hirange)))
        count = count+1
        X = amplitude * np.exp(-t / tau)
        myList.append(X)
    

    你不需要 x 是一个列表,sino un float。为此,您需要删除 []

    【讨论】:

    • 你的意思是myList[-1]?请参阅Python tutorial。您删除了问题:S
    猜你喜欢
    • 2018-05-13
    • 2018-04-02
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-17
    • 2021-06-15
    • 1970-01-01
    相关资源
    最近更新 更多