返回一个包含tup中元素位置索引的列表

2024-06-09 17:24:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python的初学者,我正在做一个需要使用带参数的函数的例子

我想创建一个functin“findElement”,它接收一个元素和一个元组,并返回一个包含元素在元组中的位置索引的列表。为此,我尝试创建如下函数:

 def findElement(elm=1, tup1= (1,2,3,4,1)):

   for i in tup1:
    if i == elm:
        print(i)

“1”是元素,(1,2,3,4,1)是元组,但出现了错误。你知道为什么吗


Tags: 函数in元素列表for参数ifdef
2条回答

我将使用for i in range(len(tup1)):来获取当前读取元素的索引

def findElement(elm=1, tup1=(1,2,3,4,1)):
   """
   Return the indexes where the element is present
   """

   # We initiate the variable that will contain the list of index
   result = [] 

   # i will give us here the index of currently read element (tup1)
   for i in range(len(tup1)):
      if tup1[i] == elm:
          result.append(i)

   return result

以下是一些方法,按我的喜好排列。第二个使用generator

列表理解:

tup = (1, 2, 3, 4, 1)

[x for x in range(len(tup)) if tup[x]==1]  # [0, 4]

发电机功能方法:

def findel(el, tup):
    for i in range(len(tup)):
        if tup[i] == el:
            yield i

list(findel(1, (1, 2, 3, 4, 1)))  # [0, 4]

不带生成器的函数方法:

def findel(el, tup):
    result = []
    for i in range(len(tup)):
        if tup[i] == el:
            result.append(i)
    return result

findel(1, (1, 2, 3, 4, 1))  # [0, 4]

相关问题 更多 >