简体   繁体   中英

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

Given an iterable consisting of a finite set of elements:

(a, b, c, d)

as an example

What would be a Pythonic way to generate the following (pseudo) ordered pair from the above iterable:

ab
ac
ad
bc
bd
cd

A trivial way would be to use for loops, but I'm wondering if there is a pythonic way of generating this list from the iterable above ?

Try using combinations .

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

will give you an iterator, you can loop over it or convert it into a list with list(combinations)

In order to only include pairs as in your example, you can pass 2 as the argument:

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

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

You can accomplish this in a list comprehension.

data = [1, 2, 3, 4]

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

print(repr(output))

Pulling the comprehension apart, it's making a tuple of the first member of the iterable and the first object in a list composed of all other members of the iterable. data[n:] tells Python to take all members after the nth.

Here it is in action.

Use list comprehensions - they seem to be considered pythonic.

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

Obtain the n-digit binary numbers, in string format, where only two of the digits are one and n is the length of the items.

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]

Find the indices of the ones for each combination.

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

Use the indices to select the items, then sort.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM