Python 编写一个函数,该函数接受一个列表作为参数,并返回一个与列表中的元素重复的列表

Python 编写一个函数,该函数接受一个列表作为参数,并返回一个与列表中的元素重复的列表,python,Python,我试图编写一个函数,它接受一个输入,例如[1,2,3],并返回[1,1,2,2,3,3],但我得到了一个错误 这是我现在的代码 def problem3(aList): list1= [] newList1= [] for i in range (len(aList)): list1.append(aList[i]) for i in range (0, len(list1)): newList1= aList + list1[i]

我试图编写一个函数,它接受一个输入,例如[1,2,3],并返回[1,1,2,2,3,3],但我得到了一个错误

这是我现在的代码

def problem3(aList):
    list1= []
    newList1= []
    for i in range (len(aList)):
        list1.append(aList[i])
    for i in range (0, len(list1)):
        newList1= aList + list1[i]
这就是错误所在

“回溯(最近一次呼叫最后一次): Python Shell,提示符2,第1行 文件“h:\TowlertonEvanDA7.py”,第34行,在 newList1=aList+list1[i] builtins.TypeError:只能将列表(而不是“int”)连接到列表“

不能将整数“添加”到列表中;这只适用于两个列表

newList1 = aList + list1[i]
可以是以下任一项:

newList1 = aList + [list1[i]]
newList1 = aList.append(list1[i])
newList1 = aList.extend([list1[i]])
但是,请注意,这些不会修复您的程序——它们只允许它运行。您的逻辑没有按照正确的顺序构建新列表。它目前将生产[1,2,3,1,2,3]

您需要的逻辑将添加一个元素两倍于您第一次接触它。批评性声明可能是这样的:

对于列表中的项目:
newList.extend([item,item])

您的第二个for循环应该是:

    newList1.append(aList[i])
    newList1.append(list1[i])
甚至:

    newList1.append(aList[i])
    newList1.append(alist[i])

因此不需要列表1。

您可以这样做:

def problem3(aList):
    newList1= []
    for i in aList:
        newList1.extend((i, i))
    return newList1

lst = [1,2,3]
print problem3(lst)

# [1, 1, 2, 2, 3, 3]

首先,不能将列表与元素组合。 第二,第一个for循环不是必需的

您可以这样做:

    def problem3New(aList):
        buffer = aList
        newList = []
        for a,b in zip(aList, buffer):
            newList.append(a)
            newList.append(b)
        return newList

根据您收到的错误,看起来您正在混合您的类型(即,您正在尝试添加带有列表的整数)

如代码第二个for循环中所述,您有:

    newList1= aList + list1[i]
也就是说:

将newList1设置为list1加上我们现在看到的任何元素

您可能希望将当前元素的两个附加到
newList1

在不太修改代码的情况下,最简单的方法是什么

请确保在函数结束时
返回newList1
(否则调用
problem3
的地方将看不到结果)

但是,您完全可以简化此代码

def problem3(aList):
    newList1 = []

    # iterate over list by its elements
    for x in aList:
        newList1.append(x)
        newList1.append(x)

    return newList
但是,有许多不同的方法(大多数更好)可以写出这个解决方案

def problem3(aList):
    newList1 = []

    # iterate over list by its elements
    for x in aList:
        newList1.append(x)
        newList1.append(x)

    return newList