简体   繁体   English

如何隔离已添加n次的列表元素?

[英]How to isolate list elements that have been added n times?

I have the following code which takes a user input for the number of spaces along a road and should return a randomised list with a 1 representing a car and 0 nothing. 我有以下代码,该代码接受用户输入的道路空间数量,并返回一个随机列表,其中1代表汽车,0代表零。 This is then repeated across all road densities ranging from 0 to 1 and the distributions are randomised. 然后在从0到1的所有道路密度上重复此操作,并随机分配分布。

spacenum = int(input("Enter number of road spaces:"))
    i=0
    while i<= spacenum:
        a.append([1]*i)
        a.append([0]*(spacenum-(i)))
        random.shuffle(a)
        print (str(a).strip('],'))
        a.clear()
        i+=1

And this produces the following lists for n=3: 这将为n = 3生成以下列表:

Enter number of road spaces:3
[[], [0, 0, 0]]
[[1], [0, 0]]
[[0], [1, 1]]
[[1, 1, 1], []]

What is happening is each chunk of 1's or 0's is sticking together as an element, which is not what I intended. 发生的是1或0的每个块都作为一个元素粘在一起,这不是我想要的。 How do I rewrite my code so that each 1's and 0's are evenly spread throughout each list. 如何重写我的代码,以使每个1和0均匀分布在每个列表中。 Thanks for your help. 谢谢你的帮助。

You seem to be trying to extend a list by appending a list at the end. 您似乎正在尝试通过在末尾附加列表来扩展列表。 Use a.extend() instead. 请改用a.extend()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM