簡體   English   中英

從可迭代對象(例如列表或集合)生成偽有序對列表的Python方法

[英]Pythonic way to generate a pseudo ordered pair list from an iterable (e.g. a list or set)

給定一個由一組有限元素組成的可迭代對象:

(A B C D)

舉個例子

從上述可迭代項生成以下(偽)有序對的Pythonic方法是什么:

ab
ac
ad
bc
bd
cd

一個簡單的方法是使用循環,但是我想知道是否存在一種從上面的可迭代方法生成此列表的pythonic方法?

嘗試使用組合

import itertools
combinations = itertools.combinations('abcd', n)

將為您提供一個迭代器,您可以對其進行循環或將其轉換為具有list(combinations)

為了像示例中那樣僅包含對,可以將2作為參數傳遞:

combinations = itertools.combinations('abcd', 2)

>>> print list(combinations)
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]

您可以通過列表理解來實現。

data = [1, 2, 3, 4]

output = [(data[n], next) for n in range(0,len(data)) for next in data[n:]]

print(repr(output))

將理解分離開來,它使iterable的第一個成員和由iterable的所有其他成員組成的列表中的第一個對象成為一個元組。 data[n:]告訴Python在第n個之后接受所有成員。

它在起作用。

使用列表理解-它們似乎被認為是pythonic。

stuff = ('a','b','c','d')

以字符串格式獲取n位二進制數字,其中只有兩位為1 ,n為項的長度。

n = len(stuff)
s = '{{:0{}b}}'.format(n)
z = [s.format(x) for x in range(2**n) if s.format(x).count('1') ==2]

找到那些每個組合的指數。

y = [[i for i, c in enumerate(combo) if c == '1'] for combo in z]

使用索引選擇項目,然后排序。

x = [''.join(operator.itemgetter(*indices)(stuff)) for indices in y]
x.sort()

暫無
暫無

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

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