如何在两个列表中连接字符串,然后从列表中分离字符串?

时间:2017-06-11 15:06:40

标签: python string list

在下面的游戏中,我想要打印3.然后是玩家在下一次尝试中正确使用的每个数字。我该如何管理它?

#pi memory game  
from sys import exit 
pi = '3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679'
x = (pi.split('.'))[1] 
right_ans = [] 
print (x) 
turns = 0  
while turns <= 3:   
    i = 0   
    while i<len(x):
        u = input("3.?")
        if u == x[i]:
            right_ans.append(x[i])
            print ("right")
            i +=1 
        else:
            turns += 1
            print ("Turns remain: ", (3-turns))
        if turns == 3:
            print ("Your guesses are over!! You managed %d digits after 3" % len(right_ans))
            exit(0)

1 个答案:

答案 0 :(得分:0)

以下是您的代码中存在错误的内容以及我修复它的建议: - )

  

1- 字符串已经是列表。您可以在没有split()的情况下循环遍历字符1:

for x in '3.1415...':
  

2- 偏好raw_input()而不是input() 。根据您的python版本,input()将输入值强制转换为string或int。 总是失败

'1' == input()
  

3-为了最大限度地降低无限循环的风险,请始终优先选择for loops   while loops什么时候可以

最后,

  

4-为了简单,减少计数器并检查它们何时   达到0,而不是在代码中使用魔术值(turns   这里)

以下是我对工作游戏的提议:

#pi memory game  
from sys import exit 
pi = '3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679'
right_ans = [] 
turns = 3
for x in pi[2:]:
    while turns > 0:
        print ("you have to guess:",x,type(x))
        u = raw_input() #Preferred to input(), so 'u' is a string
        print ("you have typed:",u,type(u))
        if u == x:
            right_ans.append(x)
            print ("right")
            break
        turns -= 1
        print ("Turns remain: ", turns)

if turns == 0:
    print ("Your guesses are over!! You managed %d digits after 3" % len(right_ans))
else:
    print ("Good job! You guessed all %d digits after 3" % len(right_ans))