在for循环中将列表追加到新列表 [英] Appending lists to new list in for loop

查看:90
本文介绍了在for循环中将列表追加到新列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试使用python中的列表,并尝试创建一个程序来模拟名称游戏(点击此处获取参考).

I am currently experimenting with lists in python and am trying to create a program that will simulate the name game (click here for refrence).

程序要求用户输入并生成一个列表,其中包含用户名的每个字母.但是,它随后必须生成3个新名称,每个名称以"b","f","m"开头.这是我遇到问题的地方.当附加到master_list时,稍后打印我的结果时,我得到输出:

The program asks for user input and generates a list with each letter of the user's name. However, it then has to generate 3 new names, each beginning with "b", "f", "m". This is where I run into a problem. When appending to master_list, and later printing my result I get the output:

[['m', 'o', 'b', 'e', 'r', 't'], ['m', 'o', 'b', 'e', 'r', 't'], 
['m', 'o', 'b', 'e', 'r', 't']]

当用户输入="Robert"

When user input = "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时的预期输出应为:

The intended output when master_list is printed should be:

[['b', 'o', 'b', 'e', 'r', 't'], ['f', 'o', 'b', 'e', 'r', 't'], 
['m', 'o', 'b', 'e', 'r', 't']]

有人对为什么会这样有想法吗?

Does anyone have ideas as to why this is happening?

推荐答案

尽管您已将变量命名为 new_list ,但事实是您在每个相同的 old 列表上进行操作时间.要修改列表并保留原始列表,您需要复制列表:

Although you named your variable new_list, the fact is you were operating on the same old list each time. To modify a list, and retain the original, you need to copy the list:

# 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']]
%

这篇关于在for循环中将列表追加到新列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆