簡體   English   中英

如何獲取不包含在python組合列表中的元素?

[英]How to get element not included in combinations list in python?

我有3個很大塊的生成器。 我正在從中創建2個元素的組合,但是在代碼的某些部分中,我需要第三部分(組合中未包含的那一部分)。 我該怎么辦? 我不需要最簡單或最漂亮的解決方案,而是需要最快的解決方案。

例:

a = ['a','b','c']
gen = chunks(a, 2) # this is not important
for x in combinations(gen, 2):
    # let's say we have x = ['a','b'] and I want to get 'c'
    # I know it is possible to put all generator elements in list and get 'c' 
    # with for loop or set, but I don't if this is the fastest way to get it

作為一種有效的方法,我建議定義一個函數,您可以多次使用它,並獲得與set的區別,因為它是pythonic快速的方法:

>>> def diff(test_array=[],main_array=['a','b','c']):
...  return set(main_array).difference(set(test_array)).pop()
... 
>>> diff(['a','b'])
'c'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM