1

我正在尝试使用用户制作的功能打印列表的所有元素。

y = [1,2,3]
def ash(list1):
for x in range(len(list)):
    return list[x],x

我想要做的是返回列表中的所有值及其索引,但我得到的只是一个元素。我可以让元素打印但不返回。

4

4 回答 4

5

您将在第一次迭代中返回。相反,您需要在函数中创建一个列表,并将所有元组添加到该列表中,最后返回该列表。

对于同时获取索引和元素,您可以使用enumerate()

def ash(list1):
    new_list = []
    for x, elem in enumerate(list1):
        new_list.append((elem,x))
    return new_list

或者,更好的是,您可以简单地使用列表推导:

return [(elem, x) for x, elem in enumerate(list1)]

前两种方法在内存中创建列表。如果您有一个非常大的列表要处理,那么您可能应该使用生成器,使用yield关键字:

def ash(list1):
    for x, elem in enumerate(list1):
        yield elem, x
于 2013-08-28T16:24:30.423 回答
2

enumerate(list)就是你要找的。(见文档)。此外,return在调用函数时,调用只会给你列表的第一个值,你想要的可能是yield语句

def ash(list):

  for i,item in enumerate(list):
    yield item,i

if __name__ == '__main__':

  y = [1,2,3]

  ys_with_indices = list(ash(y)) 
  print ys_with_indices

请注意,这将返回一个生成器对象,您必须通过对其调用 list() 将其转换为列表。或者,只需使用将各个值附加到的普通列表:

def ash(list):

  items_with_indices = []

  for i,item in enumerate(list):
    items_with_indices.append((item,i))

  return items_with_indices

if __name__ == '__main__':

  y = [1,2,3]

  ys_with_indices = ash(y)
  print ys_with_indices
于 2013-08-28T16:23:48.030 回答
2

Some issues with your code:

  1. Don't iterate using range unless necessary. Iterate the list directly, or here, use enumerate
  2. Don't use list as a variable - you'll shadow the built-in of the same name. It's confusing to the reader.
  3. You're returning out of the loop. This is why you only get the first iteration. If you want to return successive values, use yield, which turns your function into a generator:

    def ash(l):
        for x in range(len(l)):
            yield l[x],x
    
  4. This is really a reimplementation of enumerate:

    list(enumerate('abc')) #=> [(0, 'a'), (1, 'b'), (2, 'c')]
    
  5. If you really want to swap the order of the pairs, you can do:

    [b,a for a,b in enumerate('abc')]
    
  6. Alternative implementation: l='abc';zip(l,xrange(len(l)))

于 2013-08-28T16:30:31.547 回答
0
def ash(lst):    
    return [(lst[x],x) for x in range(0,len(lst))]

您将获得一个元组列表,其中元组的第一个值是原始列表的元素,第二个值是列表中元素的索引。对于 y =[1,2,3]结果是[(1, 0), (2, 1), (3, 2)]

于 2013-08-28T16:32:51.417 回答