我目前正在试验python中的列表,我正在尝试创建一个模拟名称游戏(click here for reference)的程序。
程序要求用户输入并生成包含用户姓名的每个字母的列表。然后它必须生成3个新名称,每个名称以"b", "f", "m"
开头。
所以罗伯特会成为:
[['b', 'o', 'b', 'e', 'r', 't'], ['f', 'o', 'b', 'e', 'r', 't'],
['m', 'o', 'b', 'e', 'r', 't']]
但是,如果名称以相同的字母开头,则首先删除第一个字母,因此Billy会成为
[['i', 'l', 'l', 'y'], ['f', 'i', 'l', 'l', 'y'], ['m', 'i', 'l',
'l', 'y']]
但是,当我运行我的代码而不是输出时:
[['b', 'i', 'l', 'l', 'y'], ['f', 'i', 'l', 'l', 'y'], ['m', 'i',
'l', 'l', 'y']]
有人可以帮忙吗?我的条件是否有错误?继承我的代码:
# 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)
# if new_list[0] != 'B' or new_list[0] != 'F' or new_list[0] != 'M':
if 'B' not in new_list or 'F' not in new_list or 'M' not in new_list:
new_list.pop(0)
new_list.insert(0, var)
master_list.append(new_list)
else:
new_list.pop(0)
master_list.append(new_list)
print(master_list)
我在条件声明中做了一个小的修正。在您的原始程序中,else
块被跳过。在这种方法中,我们首先检查要删除的值,然后在代码的else
块中执行替换。其次,该程序区分大小写。条件语句中有大写字符,但在列表中,它们是小写的。在下面的方法中,它们都是小写的。如果您希望它是健壮的,您可以在执行任何操作之前添加or
或将输入转换为小写。
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)
if (("b" in new_list) or ("f" in new_list) or ("m" in new_list)):
new_list.pop(0)
#new_list.insert(0,)
master_list.append(new_list)
else:
new_list.pop(0)
new_list.insert(0,var)
master_list.append(new_list)
print(master_list)
输出是
Enter name here: john
[['b', 'o', 'h', 'n'], ['f', 'o', 'h', 'n'], ['m', 'o', 'h', 'n']]
Enter name here: billy
[['i', 'l', 'l', 'y'], ['i', 'l', 'l', 'y'], ['i', 'l', 'l', 'y']]