📜  Python - 每第 N 个索引追加列表

📅  最后修改于: 2022-05-13 01:54:19.363000             🧑  作者: Mango

Python - 每第 N 个索引追加列表

给定 2 个列表,每第 n 个索引将列表附加到原始列表。

方法#1:使用循环

这是解决这个问题的蛮力方法,在这种情况下,每个第 n 个索引,内循环用于附加所有其他列表元素。

Python3
# Python3 code to demonstrate working of 
# Append List every Nth index
# Using loop
  
# initializing list
test_list = [3, 7, 8, 2, 1, 5, 8, 9, 3]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing Append list 
app_list = ['G', 'F', 'G']
  
# initializing N 
N = 3
  
res = []
for idx, ele in enumerate(test_list):
      
    # if index multiple of N
    if idx % N == 0:
        for ele_in in app_list:
            res.append(ele_in)
    res.append(ele)
  
# printing result 
print("The appended list : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Append List every Nth index
# Using extend()
  
# initializing list
test_list = [3, 7, 8, 2, 1, 5, 8, 9, 3]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing Append list 
app_list = ['G', 'F', 'G']
  
# initializing N 
N = 3
  
res = []
for idx, ele in enumerate(test_list):
      
    # if index multiple of N
    if idx % N == 0:
          
        # extend to append all elements
        res.extend(app_list)
          
    res.append(ele)
  
# printing result 
print("The appended list : " + str(res))


输出:

方法#2:使用extend()

解决这个问题的另一种方法。在这里,我们使用 extend 来获取每个第 N 个索引中的所有元素,而不是内部列表。

蟒蛇3

# Python3 code to demonstrate working of 
# Append List every Nth index
# Using extend()
  
# initializing list
test_list = [3, 7, 8, 2, 1, 5, 8, 9, 3]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing Append list 
app_list = ['G', 'F', 'G']
  
# initializing N 
N = 3
  
res = []
for idx, ele in enumerate(test_list):
      
    # if index multiple of N
    if idx % N == 0:
          
        # extend to append all elements
        res.extend(app_list)
          
    res.append(ele)
  
# printing result 
print("The appended list : " + str(res))

输出: