📜  Python|追加奇数元素两次

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

Python|追加奇数元素两次

给定一个数字列表,任务是从初始列表创建一个新列表,条件是每个奇数元素附加两次。

以下是实现上述任务的一些方法。

方法 #1:使用列表推导

# Python code to create a new list from initial list
# with condition to append every odd element twice.
  
# List initialization
Input = [1, 2, 3, 8, 9, 11]
  
# Using list comprehension 
Output = [elem for x in Input for elem in (x, )*(x % 2 + 1)]
  
# printing 
print("Initial list is:'", Input)
print("New list is:", Output)
输出:
Initial list is:' [1, 2, 3, 8, 9, 11]
New list is: [1, 1, 2, 3, 3, 8, 9, 9, 11, 11]


方法 #2:使用 itertools

# Python code to create a new list from initial list
# with condition to append every odd element twice.
   
# Importing
from itertools import chain
   
# List initialization
Input = [1, 2, 3, 8, 9, 11]
   
# Using list comprehension  and chain
Output = list(chain.from_iterable([i] 
              if i % 2 == 0 else [i]*2 for i in Input))
   
# printing 
print("Initial list is:'", Input)
print("New list is:", Output)
输出:
Initial list is:' [1, 2, 3, 8, 9, 11]
New list is: [1, 1, 2, 3, 3, 8, 9, 9, 11, 11]


方法 #3:使用 Numpy 数组

# Python code to create a new list from initial list
# with condition to append every odd element twice.
  
# Importing
import numpy as np
  
# List initialization
Input = [1, 2, 3, 8, 9, 11]
Output = []
  
# Using Numpy repeat
for x in Input:
    (Output.extend(np.repeat(x, 2, axis = 0))
      if x % 2 == 1 else Output.append(x))
  
# printing 
print("Initial list is:'", Input)
print("New list is:", Output)
输出:
Initial list is:' [1, 2, 3, 8, 9, 11]
New list is: [1, 1, 2, 3, 3, 8, 9, 9, 11, 11]