繁体   English   中英

如何从列表中打印尚未打印的项目?

[英]How to print items from list that haven't been printed?

我的问题是,如何仅打印未打印的项目? (这只是代码的一部分)。 我有一个15个项目的数组,必须将它们洗牌,然后仅打印e/2的数量。 我尝试通过使用数组中项目的索引创建第二个列表,然后仅打印列表中存在的索引和项目。 如果索引不在我的列表中,则不会打印该索引。 每次打印后,该项目的索引都会从我的虚构列表中删除,因此不会第二次打印。

def tryitem(self,c,list1):
    if c not in lista:
        c = random.randint(0, 14)
        self.tryitem(c,list1)
    else:
        pass


 ...some code...


 list1 = list(range(15))
 for i in range(int(e/2)):
             c = random.randint(0, 14)
             print(c)
             self.tryitem(c,list1)
             but= ttk.Button(root, text=str(item.myItem[c][0])+" x"+str(item.myItem[c][1]))
             but.place(anchor=W,x=20,y=wysokosc,width=170,height=25)
             wysokosc+=25
             list1.remove(item.myItem[c][2])

项目的索引位于myItem[c][2]列首先,此方法无法正常工作,因为它将某些项目打印了2至3次,并且在执行一些打印后出现错误

ValueError:list.remove(x):x不在列表中

我将尝试回答第一个问题,假设您有一个列表,并且希望以某种迭代方式打印它的项目,并且希望跟踪已经打印了哪些项目以免再次打印它们。

最简单的方法是使用字典。 每次打印项目时,请将其索引添加到字典中。 每次您要打印项目时,请检查其索引是否在词典中,并且仅在不存在时才打印。

import random

e = random.randint(1, 30)
lst = [random.randint(1, 1000) for _ in range(100)]
printed = {}  # To save if we perinted this index already

def print_next_values():
    for x in range(int(e/2)):  # print (e/2) items
        index = random.randint(0, len(lst) - 1)
        # Try to fetch new indexes until we get a new index we havn't printed yet
        while index in printed:
            index = random.randint(0, len(lst) - 1)

        print(lst[index])  # Printing the item
        printed[index] = True  # Adding the item index to the dictionary

while len(printed.keys()) < len(lst):
    print_next_values()

在这里,您可以看到一千个项目的列表,这些项目将被打印成部分(每次迭代e / 2,直到没有更多项目为止)。 在打印项目之前,我们将检查他是否已经被打印。 如果没有,我们将其打印出来。

暂无
暂无

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

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