Python:同时在for循环中添加到列表列表 - python

我想用for循环外的0索引值创建一个新列表,然后使用for循环添加到相同的列表。我的玩具示例是:

import random

data = ['t1', 't2', 't3']

masterlist = [['col1', 'animal1', 'animal2', 'animal3']]
animals = ['cat', 'dog', 'chinchilla']

for item in data:
    masterlist.append([item])
    for animal in animals:
        number1 = random.randint(1, 100)
        number2 = random.randint(1, 100)
        masterlist.append([str(number1) + ',' + str(number2)])

masterlist  

但这输出:

[['col1', 'animal1', 'animal2', 'animal3'],
 ['t1'],
 ['52,69'],
 ['8,77'],
 ['75,66'],
 ['t2'],
 ['67,33'],
 ['85,60'],
 ['98,12'],
 ['t3'],
 ['60,34'],
 ['25,27'],
 ['100,25']]

我想要的输出是:

[['col1', 'animal1', 'animal2', 'animal3'],
 ['t1', '52,69', '8,77', '75,66'], 
 ['t2', '67,33', '85,60', '98,12'],
 ['t3', '60,34', '25,27', '100,25']]

python大神给出的解决方案

这个解决方案会重构您的代码吗?

解决方案1

import random

data = ['t1', 't2', 't3']

masterlist = [['col1', 'animal1', 'animal2', 'animal3']]
animals = ['cat', 'dog', 'chinchilla']

for item in data:
    rv = []
    rv.append(item)
    for animal in animals:
        number1 = random.randint(1, 100)
        number2 = random.randint(1, 100)
        rv.append(str(number1) + ',' + str(number2))
    masterlist.append(rv)

输出:

>>> masterlist
[['col1', 'animal1', 'animal2', 'animal3'],
 ['t1', '88,43', '85,62', '84,21'],
 ['t2', '44,99', '32,54', '83,50'],
 ['t3', '82,87', '90,83', '91,84']]

或者,以下内容将给出相同的结果。

解决方案2

import random

data = ['t1', 't2', 't3']

masterlist = [['col1', 'animal1', 'animal2', 'animal3']]
animals = ['cat', 'dog', 'chinchilla']

for item in data:
    masterlist.append([item] + [f"{random.randint(1, 100)},{random.randint(1, 100)}" for animal in animals])

如何在Matplotlib条形图后面绘制网格线 - python

x = ['01-02', '02-02', '03-02', '04-02', '05-02'] y = [2, 2, 3, 7, 2] fig, ax = plt.subplots(1, 1) ax.bar(range(len(y)), y, width=…

对于DataFrame的每一行,在给定条件的情况下获取第一列的索引到新列中 - python

这是我的数据框的一部分。data = [ ['1245', np.nan, np.nan, 1.0, 1.0, ''], ['1246', np.nan, 1.0, 1.0, 1.0, ''], ['1247', 1.0, 1.0, 1.0, 1.0, �…

在Flask中测试文件上传 - python

我在Flask集成测试中使用Flask-Testing。我有一个表单,该表单具有我要为其编写测试的徽标的文件上传,但是我不断收到错误消息:TypeError: 'str' does not support the buffer interface。我正在使用Python3。我找到的最接近的答案是this,但是它对我不起作用。这是我的许多尝…

搜索csv文件,最佳实践是什么? - python

我有一个看起来像这样的CSV文件:(在我的CSV文件中没有标题,但为清楚起见,我在此处添加了标题)geneName, personNumber, allele1, allele2 gene-1-A, PERSON1, C, G gene-2_s, PERSON1, A, C gene_3_D, PERSON1, T, T . . . gene-1_A, PE…

如果__name__ =='__main__',则为Python的Powershell等效项: - python

我真的很喜欢python的功能,例如:if __name__ == '__main__': #setup testing code here #or setup a call a function with parameters and human format the output #etc... 很好,因为我可以将Python脚本文件…