我目前正在尝试使用python中的列表,并试图创建一个程序来模拟名称游戏(click here for refrence)。
程序要求用户输入并生成一个列表,其中包含用户名的每个字母。但是,它随后必须生成3个新名称,每个名称以“ b”,“ f”,“ m”开头。这是我遇到问题的地方。当追加到master_list时,稍后打印我的结果时,我得到输出:
[['m', 'o', 'b', 'e', 'r', 't'], ['m', 'o', 'b', 'e', 'r', 't'],
['m', 'o', 'b', 'e', 'r', 't']]
当用户输入=“ Robert”时
这里是我的代码:
# Asks for user name
user_name = input("Enter name here: ")
name = list(user_name)
# Create an empty list that will contain a subsets of lists.
master_list = []
# List containing the first letter of each new name
beginning_of_word = ["b", "f", "m"]
# Creates 3 new names and appends them to master_list
for var in beginning_of_word:
new_list = name
new_list.pop(0)
new_list.insert(0, var)
print(new_list)
master_list.append(new_list)
if new_list != name:
new_list = name
打印master_list时的预期输出应为:
[['b', 'o', 'b', 'e', 'r', 't'], ['f', 'o', 'b', 'e', 'r', 't'],
['m', 'o', 'b', 'e', 'r', 't']]
有人对为什么会这样有想法吗?
答案 0 :(得分:2)
尽管您将变量命名为new_list
,但事实是您每次都在同一个 old 列表中进行操作。要修改列表并保留原始列表,您需要复制列表:
# Asks for user name
user_name = input("Enter name here: ")
name = list(user_name)
# Create an empty list that will contain a subsets of lists.
master_list = []
# List containing the first letter of each new name
beginning_of_word = ["b", "f", "m"]
# Creates 3 new names and appends them to master_list
for var in beginning_of_word:
new_list = list(name) # a copy of 'name'
new_list[0] = var
master_list.append(new_list)
print(master_list)
输出
% python3 test.py
Enter name here: Robert
[['b', 'o', 'b', 'e', 'r', 't'], ['f', 'o', 'b', 'e', 'r', 't'], ['m', 'o', 'b', 'e', 'r', 't']]
%