2017-03-10 80 views
1

我正在尝试编写一个函数,该函数接受例如[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] 

这是错误

"Traceback (most recent call last): Python Shell, prompt 2, line 1 File "h:\TowlertonEvanDA7.py", line 34, in newList1= aList + list1[i] builtins.TypeError: can only concatenate list (not "int") to list"

回答

0

你不能给列表“添加”一个整数;这只适用于两个列表。

newList1 = aList + list1[i] 

可能是下列任何一项:然而

newList1 = aList + [list1[i]] 
newList1 = aList.append(list1[i]) 
newList1 = aList.extend([list1[i]]) 

注意的是,这些不会解决你的程序 - 他们将仅仅允许它运行。您的逻辑不会以正确的顺序构建新列表。它目前会产生[1,2,3,1,2,3]。

您需要的逻辑会在您第一次触摸时添加一个元素两次。关键语句应该是这样的:在ALIST

的项目: newList.extend([项目,项目])

0

您的循环第二应该是这样的:

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

甚至:

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

因此不需要list1。

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] 
0

首先,你不能用一个元素相结合的列表。其次,第一个for循环不是必需的。

你可以这样说:

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

基于关你得到它看起来像你的混合类型(如你想添加与列表整数错误)。

如第二for循环代码的注意,你必须:

newList1= aList + list1[i] 

这是说:

Set newList1 to list1 plus whichever element we're looking at now

你可能寻找到替代追加两您正在查看的当前元素为newList1

为了什么可能是这样做的最直接的方式(无需修改代码太多):

for i in range(0, len(list1)): 
    # append current element twice to the end of our new list 
    newList1.append(list1[i]) 
    newList1.append(list1[i]) 

确保也return newList1你的函数结束(或者你不会看到你的来自任何你称为problem3)。

你绝对可以简化此代码然而

def problem3(aList): 
    newList1 = [] 

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

    return newList 

有许多不同的方式(大部分是更好),但是你可以写这个解决方案出来。

相关问题