[英]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) (A B C D)
as an example 举个例子
What would be a Pythonic way to generate the following (pseudo) ordered pair from the above iterable: 从上述可迭代项生成以下(伪)有序对的Pythonic方法是什么:
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 ? 一个简单的方法是使用循环,但是我想知道是否存在一种从上面的可迭代方法生成此列表的pythonic方法?
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)
将为您提供一个迭代器,您可以对其进行循环或将其转换为具有list(combinations)
In order to only include pairs as in your example, you can pass 2 as the argument: 为了像示例中那样仅包含对,可以将2作为参数传递:
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. 将理解分离开来,它使iterable的第一个成员和由iterable的所有其他成员组成的列表中的第一个对象成为一个元组。 data[n:]
tells Python to take all members after the nth. data[n:]
告诉Python在第n个之后接受所有成员。
Use list comprehensions - they seem to be considered pythonic. 使用列表理解-它们似乎被认为是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位二进制数字,其中只有两位为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]
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.