【问题标题】:How to print items from list that haven't been printed?如何打印列表中尚未打印的项目?
【发布时间】:2017-10-28 09:52:48
【问题描述】:

我的问题是,如何只打印尚未打印的项目? (这只是代码的一部分)。 我有一个包含 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] 列 首先这个方法不能正常工作,因为它打印了一些项目两到三遍,在打印一些之后我得到了错误

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

【问题讨论】:

  • 用字典代替列表。
  • 什么是eexp(1)?
  • 不,它只是一个介于 1 和 30 之间的数字

标签: python


【解决方案1】:

我将尝试回答您的第一个问题,假设您有一个列表并且您想在某种迭代中打印它的项目,并且您想跟踪已经打印的项目以便不再打印它们.

最简单的方法是使用字典。 每次打印一个项目时,将他的索引添加到字典中。 每次要打印一个项目时,检查他的索引是否在字典中,如果没有就打印。

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()

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-03
    • 1970-01-01
    • 2022-08-08
    相关资源
    最近更新 更多