Python:打印列表(由 2 个列表连接)显示“”或 ' '

问题描述 投票:0回答:1

我制作了一个名为“scramble”的列表。 该列表是通过随机添加 2 个列表(move1 和 move2)的值来创建的

当我打印列表时,答案被“”或''包围。

示例:

scramble = ['U', 'F2', 'B', 'R2', "U'", 'R', "R'", 'D', 'L2', 'B2', "U'", 'R2', "R'", 'F', "D'"]

我的代码:

import random as rd

scramble = []
move1 = ["F","R","L","U","B","D"]
move2 = ["","'","2"]

while len(scramble) < 15:
    s = move1[rd.randint(0, 5)]
    t = move2[rd.randint(0, 2)]
   
    scramble.append(s+t) 

我真的很想了解为什么会发生这种情况。

然后改正它。

我想他们有几种在创建列表后清理“”和“”的方法。 但是:

  1. 我发现这个解决方案不是最优的。
  2. 我还希望“move1”不与最后一个重复。 我本来打算使用 .startwith 但我的问题是 ti 有时以 " 开头,有时以 '.
python list random rubiks-cube
1个回答
0
投票

问题是Python自动使用

'
作为字符串的开头,但是如果字符串包含
'
,Python必须使用
"
作为字符串。我不知道为什么这对你来说真的是一个问题,因为你通常可以使用移动并使用例如
scramble[4]
访问列表,或者如果你想打印它,你可以这样做:

result = ""

for move in scramble:
   result = result + move + " " # add to the preeviously created string the move from the list.

print(result)
# you can also use result to display the scramble somewhere.

为了使代码不重复其移动,您必须在生成打乱时将 for 循环更改为如下所示:

# generate the first move so that we can use it to compare it to the new move
s = move1[rd.randint(0, 5)]
t = move2[rd.randint(0, 2)]

scramble.append(s+t)

# generate 14 more moves
while len(scramble) < 15:
    # generate the move temporary
    s = move1[rd.randint(0, 5)]
    t = move2[rd.randint(0, 2)]

    move = s+t
    # comapre the last move with the temporary created move while ignoring ' or 2 and regenerate the move
    while move.replace("'", "").replace("2", "") == scramble[-1].replace("'", "").replace("2", ""):
        s = move1[rd.randint(0, 5)]
        t = move2[rd.randint(0, 2)]

        move = s+t

    scramble.append(move)

完整的代码应该如下所示:

import random as rd

scramble = []
move1 = ["F","R","L","U","B","D"]
move2 = ["","\'","2"]

# generate the first move so that we can use it to compare it to the new move
s = move1[rd.randint(0, 5)]
t = move2[rd.randint(0, 2)]

scramble.append(s+t)

# generate 14 more moves
while len(scramble) < 15:
    # generate the move temporary
    s = move1[rd.randint(0, 5)]
    t = move2[rd.randint(0, 2)]

    move = s+t
    # comapre the last move with the temporary created move while ignoring ' or 2 and regenerate the move
    while move.replace("'", "").replace("2", "") == scramble[-1].replace("'", "").replace("2", ""):
        s = move1[rd.randint(0, 5)]
        t = move2[rd.randint(0, 2)]

        move = s+t

    scramble.append(move)

result = ""

for move in scramble:
   result = result + move + " " # add to the preeviously created string the move from the list.

print(result)
# you can also use result to display the scramble somewhere.

我知道我的答案不是最好的,因为我仍然是Python的初学者,但我希望它能完成它必须做的事情并解决你的问题。

© www.soinside.com 2019 - 2024. All rights reserved.