【问题标题】:*Python* Using function parameters to repeat an element of a list within a list*Python* 使用函数参数在列表中重复列表的元素
【发布时间】:2021-07-11 19:45:59
【问题描述】:

我有一个关于 Python 中的列表操作和函数参数的问题。

假设我有这个功能

def list_and_index_repeat(a,b,c)

现在让我们说我们的 a 参数是我们的列表

list_and_index_repeat([1,2,3,4],b,c)

我们的 b 参数是我们在上述列表中的索引。

list_and_index_repeat([1,2,3,4],3,c)

interger 3 代表我们的第三个元素 4

现在我们有了元素 4 我将如何在原始列表 a

中重复这个元素 within

例子:

list_and_index_repeat([1,2,3,4],3,2)

所以我在列表中取出 第三个 元素,然后 重复 2,所以我得到了最终输出:

final_output[1,2,3,4,4,4]

谢谢,

【问题讨论】:

    标签: python list function


    【解决方案1】:

    试试:

    def list_and_index_repeat(a, b, c):
        return a[:b] + [a[b], *[a[b]] * c] + a[b + 1 :]
    
    
    out = list_and_index_repeat([1, 2, 3, 4], 3, 2)
    print(out)
    

    打印:

    [1, 2, 3, 4, 4, 4]
    

    【讨论】:

      【解决方案2】:

      从列表中切出最多 b + 1 的部分,然后将 a[b] c 次的值附加到新列表中并返回:

      def list_and_index_repeat(a,b,c):
          new_list = a[:b+1]
          
          for _ in range(c):
              new_list.append(a[b])
          
          return new_list
      
      print(list_and_index_repeat([1,2,3,4],3,2))
      

      输出:

      [1, 2, 3, 4, 4, 4]
      

      【讨论】:

        【解决方案3】:

        您可以简单地使用 list.extend() 方法来实现这一点。 例如:

        a = []
        a.extend(2 * "c")
        print(a)
        

        它会返回这个 ["c", "c"]

        【讨论】:

        • 您如何计划将 2(整数)精确地提高到“c”(字符串)的幂?即使在数学上也是不可能的,因为 c 甚至不是一个变量,它是一个文字字符串
        猜你喜欢
        • 2015-10-07
        • 2019-05-20
        • 1970-01-01
        • 2011-03-31
        • 2018-08-05
        • 1970-01-01
        • 2019-04-12
        • 2018-11-09
        • 2012-08-06
        相关资源
        最近更新 更多