在 Python 中追加奇數元素兩次
在這篇文章中,我們將看到如何獲取一個列表,其中包含一些奇數作為它的元素,然後將這些奇數元素重複新增到同一個列表中。這意味著如果列表中一個奇數存在兩次,那麼在處理後,這個奇數將存在於同一個列表中四次。
對於這一需求,我們將有許多方法,其中我們使用 for 迴圈和 in 條件,或者使用 itertools 模組。我們還透過將每個元素除以 2 來檢查奇數條件。
示例
from itertools import chain
import numpy as np
data_1 = [2,11,5,24,5]
data_2=[-1,-2,-9,-12]
data_3= [27/3,49/7,25/5]
odd_repeat_element_3=[]
# using for and in
odd_repeat_element = [values for i in data_1 for values in (i, )*(i % 2 + 1)]
print("Given input values:'", data_1)
print("List with odd number repeated values:", odd_repeat_element)
# Using chain from itertools
odd_repeat_element_2 = list(chain.from_iterable([n]
if n % 2 == 0 else [n]*2 for n in data_2))
print("\nGiven input values:'", data_2)
print("List with odd number repeated values:", odd_repeat_element_2)
# Using extend from mumpy
for m in data_3:
(odd_repeat_element_3.extend(np.repeat(m, 2, axis = 0))
if m % 2 == 1 else odd_repeat_element_3.append(m))
print("\nGiven input values:'", data_3)
print("List with odd number repeated values:", odd_repeat_element_3)執行以上程式碼,我們得到以下結果
Given input values:' [2, 11, 5, 24, 5] List with odd number repeated values: [2, 11, 11, 5, 5, 24, 5, 5] Given input values:' [-1, -2, -9, -12] List with odd number repeated values: [-1, -1, -2, -9, -9, -12] Given input values:' [9.0, 7.0, 5.0] List with odd number repeated values: [9.0, 9.0, 7.0, 7.0, 5.0, 5.0]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP