itertools是Python中的一個模塊,具有用於處理迭代器的函數集合。它們非常容易地遍曆列表和字符串之類的可迭代對象。 chain()是這樣的itertools函數之一。
注意:有關更多信息,請參閱Python Itertools。
chain()函數
它是一個需要一係列可迭代對象並返回一個可迭代對象的函數。它將所有可迭代對象組合在一起,並生成一個可迭代對象作為輸出。它的輸出不能直接使用,因此不能顯式轉換為可迭代對象。此函數在終止迭代器的類別迭代器下。
用法:
chain (*iterables)
鏈條的永恒工作可以如下實現:
def chain(*iterables):
     for it in iterables:
       for each in it:
           yeild (each)
範例1:奇數和偶數在單獨的列表中。合並它們以形成一個新的單個列表。
from itertools import chain 
  
# a list of odd numbers 
odd =[1, 3, 5, 7, 9] 
  
# a list of even numbers 
even =[2, 4, 6, 8, 10] 
  
# chaining odd and even numbers 
numbers = list(chain(odd, even)) 
  
print(numbers)[1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
範例2:列表中有一些輔音。元音在列表中給出。合並它們並對其進行排序。
from itertools import chain 
  
# some consonants 
consonants =['d', 'f', 'k', 'l', 'n', 'p'] 
  
# some vowels 
vowels =['a', 'e', 'i', 'o', 'u'] 
  
# resultatnt list 
res = list(chain(consonants, vowels)) 
  
# sorting the list 
res.sort() 
  
print(res)['a', 'd', 'e', 'f', 'i', 'k', 'l', 'n', 'o', 'p', 'u']
範例3:在下麵的示例中,每個String被認為是可迭代的,並且其中的每個字符都被視為迭代器中的一個元素。這樣就產生了每個角色
from itertools import chain 
  
res = list(chain('ABC', 'DEF', 'GHI', 'JKL')) 
  
print(res)['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L']
範例4:
from itertools import chain 
  
st1 ="Geeks"
st2 ="for"
st3 ="Geeks"
  
res = list(chain(st1, st2, st3)) 
print("before joining:", res) 
  
ans =''.join(res) 
print("After joining:", ans)before joining:[‘G’, ‘e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘G’, ‘e’, ‘e’, ‘k’, ‘s’]
After joining:GeeksforGeeks
chain.from_iterable()函數
它類似於鏈,但可用於從單個可迭代項中鏈接項目。差異在以下示例中得到了證明:
範例5:
from itertools import chain 
  
li =['ABC', 'DEF', 'GHI', 'JKL'] 
  
# using chain-single iterable. 
res1 = list(chain(li)) 
  
  
res2 = list(chain.from_iterable(li)) 
  
print("using chain:", res1, end ="\n\n") 
  
print("using chain.from_iterable:", res2)using chain:[‘ABC’, ‘DEF’, ‘GHI’, ‘JKL’]
using chain.from_iterable:[‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’, ‘G’, ‘H’, ‘I’, ‘J’, ‘K’, ‘L’]
範例6:現在考慮下麵的列表:
li=['123', '456', '789']
您應該考慮每個數字來計算列表的總和。因此答案應該是:
1+2+3+5+6+7+8+9 = 45
使用下麵的代碼可以輕鬆實現:
from itertools import chain 
  
li =['123', '456', '789'] 
  
res = list(chain.from_iterable(li)) 
  
print("res =", res, end ="\n\n") 
  
new_res = list(map(int, res)) 
  
print("new_res =", new_res) 
  
sum_of_li = sum(new_res) 
  
print("\nsum =", sum_of_li)res = ['1', '2', '3', '4', '5', '6', '7', '8', '9'] new_res = [1, 2, 3, 4, 5, 6, 7, 8, 9] sum = 45
為了簡化它,我們結合了這些步驟。下麵給出了一種優化的方法:
from itertools import chain 
  
li =['123', '456', '789'] 
  
res = list(map(int, list(chain.from_iterable(li)))) 
  
sum_of_li = sum(res) 
  
print("res =", res, end ="\n\n") 
print("sum =", sum_of_li)res = [1, 2, 3, 4, 5, 6, 7, 8, 9] sum = 45
注:本文由純淨天空篩選整理自erakshaya485大神的英文原創作品 Python – Itertools.chain()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
