【发布时间】:2021-03-06 19:16:35
【问题描述】:
我目前正在尝试创建一个包含 100 个项目的列表,每个项目都是具有 3 个值的子列表。
这些值由 randint(0,1000) 生成,每个子列表的每个值都是唯一的。 例如,如果 x1list = [1,2,3]、x2list = [4,5,6] 和 x3list = [7,8,9]... 我希望 testlist 包含 [[1,4,7], [2,5,8], [3,6,9]].
到目前为止,这是我的代码,我是编程新手,所以如果效率低/基本,我提前道歉。
import random
from random import randint
x1list = []
x2list = []
x3list = []
sublist = []
for i in range(100):
x1list.append(randint(0,1000))
x2list.append(randint(0,1000))
x3list.append(randint(0,1000))
n = 0
for i in range(100):
sublist.append(x1list[n])
sublist.append(x2list[n])
sublist.append(x3list[n])
n += 1
testlist = [[value] for value in sublist]
目标是使 testlist 成为最终的 100 个长度列表,其中包含 100 个长度为 3 的子列表,如前所述。然而,目前我对 testlist 的列表理解给了我一个长度为 300 的列表,testlist 中的每个项目都是一个随机整数值,它自己的列表。 p>
我尝试使用列表理解的另一种解决方案让我离最终目标更近了一点,但有一个不同的问题......
用这个替换 testlist 列表理解行:
testlist = [[x, y, z] for x in x1list for y in x2list for z in x3list]
生成的 testlist 包含每个 3 个值的子列表,但是 testlist 的长度为 1000000 个项目,并且似乎只更改了 1 个值(x, y 或 z,不是所有 3) 每个子列表。
关于如何获得所需结果的任何想法?我检查了其他一些 stackoverflow 帖子,它们在一定程度上帮助了我达到这一点,但我在这方面有点碰壁。
以下是我查看的帖子以使我达到这一点:
How do you turn a list of strings into a list of sublists with each string in each sublist?
Python Create a list of sublists from a list
Creating Sublists from a “List” - 最后一个对我没有多大帮助,因为我无法让 zip() 工作。
提前感谢您提供的任何帮助!
【问题讨论】:
-
你只要
[[randint(0, 1000) for _ in range(3)] for _ in range(100)]
标签: python python-3.x list