【问题标题】:why I can not get the elements from appending one list into another为什么我不能从将一个列表附加到另一个列表中获取元素
【发布时间】:2020-08-04 10:40:22
【问题描述】:

我被要求将一个列表附加到另一个空列表中(在原始列表中进行了一些更改) 我尝试了以下代码它显示错误的输出

names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
usernames=[]
change= [n.lower() for n in names]
for n in names:
    username=(n.replace(' ','_'))
usernames.append(username)
print (usernames)

预期输出:

joey_tribbiani
monica_geller
chandler_bing
phoebe_buffay

我得到了什么:

['Phoebe_Buffay']

【问题讨论】:

  • 您需要对齐您的附加语句。它正在退出 for 循环

标签: python list for-loop append empty-list


【解决方案1】:

Pythonic 的实现方式是使用list comprehension。试试这个:

names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
usernames = [n.lower().replace(' ','_') for n in names]
print (usernames)

现在,让我们跳转到您的代码。问题在于username=(n.replace(' ','_')) 行。在每次迭代中,您都在重新定义变量,并且在 for 循环的最后一次迭代之后,username 指向列表中的最后一个元素。

可能这只是缩进问题,您希望在 for 循环的每次迭代中进行 append 操作,但不小心忘记了正确缩进。我删除了username 变量并将append 移到for 循环下。试试这个:

names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
usernames = []
for n in names:
    usernames.append(n.lower().replace(' ','_'))
print(usernames)

输出:

['joey_tribbiani', 'monica_geller', 'chandler_bing', 'phoebe_buffay']

【讨论】:

    猜你喜欢
    • 2015-01-29
    • 2020-10-29
    • 1970-01-01
    • 1970-01-01
    • 2016-02-26
    • 1970-01-01
    • 2020-03-30
    • 2019-02-27
    • 1970-01-01
    相关资源
    最近更新 更多