限制列表的大小

时间:2018-04-15 10:58:38

标签: python list

如何确保列表只有一定数量的元素,之后的额外输入会被忽略?

Dim direct As New DirectoryInfo(".\")
        'Get the files based on .txt extension
Dim files As FileInfo() = direct.GetFiles("*.*")

        'loop through each files and add it to Listbox control
For Each file As FileInfo In files 
  ComboBox.Items.Add(System.IO.Path.GetFileNameWithoutExtension(file.Name))
Next

1 个答案:

答案 0 :(得分:0)

这是对我从你的问题中理解的解释:

https://pyfiddle.io/fiddle/0893e2af-726d-4fb3-9155-d83ecc5bbd55/

import random
diceboard = [1,2,0,4,5,0] #for example
def roll():
    return list(map(
        lambda x: random.randint(1,6),
        range(len(diceboard))
    ))

n=0
#this basically means that per each element 
#that does not have a value of zero(pls correct my code)
non_zero_diceboard = [d for d in diceboard if d > 0]
for i in range(len(non_zero_diceboard)):
    n=n+1
    newroll=roll()
    newroll=newroll[:n] #this limits the size of the list 
    print(newroll)