【问题标题】:Creating a list within a loop在循环中创建列表
【发布时间】:2020-07-13 06:47:32
【问题描述】:

我创建了一个“策划”风格的游戏,用户可以猜测计算机生成的确切数字序列。

我想添加一个功能来存储以前的猜测,以便在进行下一次猜测之前将它们重播给用户

在我的脑海中,根据当前的程序布局,我认为如果我可以创建一系列“pul”(以前的用户列表)会很好。

例如,当 while 循环运行并且“count”变量增加时,列表的名称会适当。

cl,计算机列表

ul,用户列表

ol,输出列表

pul,上一个用户列表

当 count = 0 时,用户输入创建 ul = [1, 3, 4, 8]

pul_0 = ul

'# 所以 pul_0 = [1, 3, 4, 8]

当 count = 1 时,用户为 ul = [2, 2, 9, 0] 创建新列表

pul_1 = ul

'# 所以 pul_1 = [2, 2, 9, 0]

'# 当然还有 pul_0 仍然 = [1, 3, 4, 8]

任何帮助表示赞赏,在此先感谢。

这里有一些代码可以提供更多细节,如果需要,底部的完整程序可以提供更多上下文。

n = int(input("how many numbers to guess? (normally 4)"))

att = int(input("how many attempts? (normally 10)"))

count = 0
while count < att:

    ul = [int(input()) for i in range(n)]

    pul(count) = ul

    count = count + 1

我读过一些关于使用字典来解决这个问题的文章,但没有让它们为我工作 create lists of unique names in a for -loop in python

{'pul_{}'.format(count):[] for i in ul}

下面的完整程序


n = int(input("how many numbers to guess? (normally 4)"))

att = int(input("how many attempts? (normally 10)"))

cl = [randint(0, 9) for i in range(n)]

wincount = 0
count = 0

while count < att:

    print(att-count, "attempts remaining. Please enter",n, "numbers, pressing enter between each")

    ul = [int(input()) for i in range(n)]



    wincount = 0
    nearcount = 0
    for i in range (n):

        if cl[i] == ul[i]:
            wincount = wincount + 1

        for j in range (n):
            if cl[i] == ul[j]:
                nearcount += 1

    nearcount = nearcount - wincount

    if wincount == n:
        print("winner")
        count = att + 1

    if wincount != n:
        print("you have", wincount,"correct numbers in the correct positions")
        print("you have a further", nearcount,"correct numbers, but they are in the wrong positions")
        count = count + 1




if count == att:

    print("no more attempts, game over")
    print("btw the correct answer was", cl)
elif count == att + 1:
    print("nice 1")


'''



I have read a small amount about using a dictionary to try and solve this issue, but i played around with it a little and didn't get very far.

Thanks in advance!

【问题讨论】:

  • 最好应用一些格式,让其他人在简要查看后不会关闭您的问题。

标签: python list loops dictionary


【解决方案1】:

这里是你的代码修改

n = int(input("how many numbers to guess? (normally 4)"))
att = int(input("how many attempts? (normally 10)"))
count = 0
pul = {}  # here're your previous lists, currently empty
while count < att:
    ul = [int(input()) for i in range(n)]
    pul[count] = ul  # you can use more flexible key value, as you mentioned
    count = count + 1
    # if you need to replay lists - you just use your "pul" dict
for i in range(count):
    print(f'your № {i} list was {pul.get(i)}')  

【讨论】:

  • 欢迎来到 StackOverflow!虽然您的代码可能会回答这个问题,但最好清楚地解释它的作用以及它为什么解决了 OP 的问题。如需进一步指导,请参阅 How do I write a good answer
猜你喜欢
  • 2019-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多