首页 > 解决方案 > 如何通过python中的用户输入(也循环)将元素从列表A移动到列表B?

问题描述

下面是我在 python 中运行的代码,以及所需的输出。我把它放在一个循环中,将多个元素(名称)移动到第二个列表,直到用户输入一个空白。唯一的问题是我无法围绕输入代码将一个名称从regularLine 移动到FastTrack。

代码:

regularLine = ["Ryan","Luke","Chase","Scotty","Brayden","Ben","James","Daniel","Carson","Nathalia","Ian","Dave"]
fastTrack = []
print("Hello, my name is Rebo and today you'll be choosing who gets to \ngo into the fast track.\n")
print("In the regular line we have {}, {}, {}, {}, {}, \n{}, {}, {}, {}, {}, {}, and {}.\n".format(*regularLine))
NotBlank = True
while NotBlank is True:
  chosenNames = input("Ready?\nEnter chosen names here:")
  regularLine.remove(input)
  fastTrack.append(input)
  print("You've now moved {} to the fast track."fastTrack)
  if chosenNames == "":
    NotBlank is False
    break;
  else:
    NotBlank is True

期望的输出:

print("You've now moved {} to the fast track.".format(*fastTrack))

如果还没看过,

      regularLine.remove(input)
      fastTrack.append(input)

是我想要输入的两行,用于从列表 A 中删除名称并将其添加到列表 B。如果我将列表转换为文件可能会更容易,但我会喜欢保持原样。

标签: pythonpython-3.xpython-2.7

解决方案


不要做 regularLine.remove(input) 做 regularLine.remove(chosenNames) 和 fastTrack 一样,但要追加。你可以把它放在一个 if 语句中,它检查是否“chosenNames in regularLine”,如果你想删除多个名称,那么我会执行以下代码:

for item in chosenNames.split():
    if item in regularLine:
        regularLine.remove(item)
        fastTrack.append(item)

推荐阅读