如何逐行打印成对的元素?

2024-10-01 17:32:41 发布

您现在位置:Python中文网/ 问答频道 /正文

guessesRemaining=12
Summary=[]


code=['1','2','3','4']



while guessesRemaining > 0:
report=[]
guess=validateInput()
guessesRemaining -= 1
if guess[0] == code[0]:
    report.append("X")
if guess[1] == code[1]:
    report.append("X")
if guess[2] == code[2]:
    report.append("X")
if guess[3] == code[3]:
    report.append("X")

tempCode=list(code)
tempGuess=list(guess)

if tempGuess[0] in tempCode:
    report.append("O")
if tempGuess[1] in tempCode:
    report.append("O")
if tempGuess[2] in tempCode:
    report.append("O")
if tempGuess[3] in tempCode:
    report.append("O")

ListCount=report.count("X")
if ListCount > 0:
    del report[-ListCount:]

report2=report[0:4]
dash=["-","-","-","-"]
report2=report+dash
report3=report2[0:4]
report4="".join(report3)
guess2="".join(guess)
Summary+=[guess2,report4]

print(Summary)

validateInput()调用了一个我没有在这里添加的函数。在12次猜测的过程中,我一直在想如何一行一行地打印我的结果。我猜了三遍。。。你知道吗

['4715', 'OO--', '8457', 'O---', '4658', 'O---']

当我想接受。。。你知道吗

['4715', 'OO--'] 
['8457', 'O---']
['4658', 'O---'] 

我尝试过以多种方式\n添加插件,但不知道如何实现它。非常感谢您的帮助。你知道吗


Tags: inreportifcodesummarylistguessdash
3条回答

如果Summary仅用于打印而不用于后续步骤

Summary+=[guess2,report4,'\n']

for i in Summary:
  print i,

另一种方法是使用How do you split a list into evenly sized chunks?中的一种解决方案

我想你需要这样的东西

In [1]: l = ['4715', 'OO ', '8457', 'O -', '4658', 'O -']

In [2]: l1 = l[::2] # makes a list ['4715', '8457', '4658']

In [3]: l2 = l[1::2] # makes ['OO ', 'O -', 'O -']

In [4]: for i in zip(l1, l2):
   ...:     print i
   ...:
('4715', 'OO ')
('8457', 'O -')
('4658', 'O -')

I've tried to add in \n in multiple ways but I can't figure out how to implement it.

如果你一开始就正确地组织数据,这会有很大帮助。你知道吗

Summary+=[guess2,report4]

这意味着“将[guess2,report4]中找到的每个项目分别附加到Summary”。你知道吗

您的意思似乎是“将[guess2,report4]作为单个项附加到Summary”。为此,需要使用列表的append方法:

Summary.append([guess2, report4])

现在我们有了一个成对的列表,每个成对的列表都要显示在单独的一行上,这样就容易多了:

for pair in Summary:
    print(pair)

相关问题 更多 >

    热门问题